import datetime
now = datetime.datetime.now()
print ("Última versión:")
print (now.strftime("%Y-%m-%d %H:%M:%S"))
import pandas as pd
import numpy as np
import pandas_profiling
from itertools import combinations
from dateutil.parser import parse
import matplotlib as mpl
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import pyplot
from matplotlib.lines import Line2D
import seaborn as sns
import plotly.express as px
#parametros de las gráficas 3d
elev = 50.0
azim = 10.0
#se define diccionario de colores
color_dict = dict({'G0':'blue',
'G1':'green',
'G2': 'orange',
'G3': 'grey',
'G4': 'red',
'G5': 'magenta'})
#personalizar leyenda
legend_elements_6 = [Line2D([0], [0], marker='o', markerfacecolor='magenta', color='w', label='G5'),
Line2D([0], [0], marker='o', markerfacecolor='red', color='w', label='G4'),
Line2D([0], [0], marker='o', markerfacecolor='grey', color='w', label='G3'),
Line2D([0], [0], marker='o', markerfacecolor='orange', color='w', label='G2'),
Line2D([0], [0], marker='o', markerfacecolor='green', color='w', label='G1'),
Line2D([0], [0], marker='o', markerfacecolor='blue', color='w', label='G0')]
legend_elements_5 = [Line2D([0], [0], marker='o', markerfacecolor='red', color='w', label='G4'),
Line2D([0], [0], marker='o', markerfacecolor='grey', color='w', label='G3'),
Line2D([0], [0], marker='o', markerfacecolor='orange', color='w', label='G2'),
Line2D([0], [0], marker='o', markerfacecolor='green', color='w', label='G1'),
Line2D([0], [0], marker='o', markerfacecolor='blue', color='w', label='G0')]
legend_elements_4 = [Line2D([0], [0], marker='o', markerfacecolor='grey', color='w', label='G3'),
Line2D([0], [0], marker='o', markerfacecolor='orange', color='w', label='G2'),
Line2D([0], [0], marker='o', markerfacecolor='green', color='w', label='G1'),
Line2D([0], [0], marker='o', markerfacecolor='blue', color='w', label='G0')]
#datos procesados
datos = pd.read_csv("C:/Users/miguel.alvarez/Google Drive/INFOTEC/Proyecto/Code-Data/Mun/1_Procesamiento/Resultados_Datos-procesados_mun2019.csv", encoding='utf-8')
print(datos.dtypes)
datos
#se reordena y eliminan del dataframe las variables que no se usarán
datos_mun = datos.drop(columns=['Coef_Var_PE', 'Var_Prop_PE', 'Autocorr_PE','Area_Km2'])
datos_mun = datos_mun.reindex(columns= ['EDO','NOMBRE_ESTADO','MUN','NOMBRE_MUNICIPIO','NUM_SECC_RUR','LNE','Densidad_LNE','Razon_LNE_PE','TC_LNE_2019','Coef_Var_LNE','Var_Prop_LNE','Autocorr_LNE'])
#verificar si hay valores nulos en datos_mun
datos_mun.isnull().sum()
#se eliminan las filas (municipios) con valores vacíos
datos_mun_limpio = datos_mun.dropna()
datos_mun_limpio = datos_mun_limpio.reset_index(drop=True) #para reordenar el índice del nuevo dataframe
datos_mun_limpio.isnull().sum()
#se transforman algunos indicadores para analizar escenarios
datos_mun_limpio_tf = datos_mun_limpio.copy()
#np-log de LNE, Densidad
datos_mun_limpio_tf['LNE'] = np.log(datos_mun_limpio_tf['LNE'])
datos_mun_limpio_tf['Densidad_LNE'] = np.log(datos_mun_limpio_tf['Densidad_LNE'])
#datos_mun_limpio_tf['NUM_SECC_RUR'] = np.log(datos_mun_limpio_tf['NUM_SECC_RUR']+1)
#se separan los indicadores de los metadatos
#metadatos
metadatos = datos_mun_limpio[['EDO', 'NOMBRE_ESTADO', 'MUN', 'NOMBRE_MUNICIPIO']]
#8 indicadores (features)
datos_mun_limpio_f = datos_mun_limpio[['NUM_SECC_RUR','LNE', 'Densidad_LNE', 'Razon_LNE_PE', 'TC_LNE_2019', 'Coef_Var_LNE', 'Var_Prop_LNE','Autocorr_LNE']]
#8 indicadores con transformación log (features)
datos_mun_limpio_f_tf = datos_mun_limpio_tf[['NUM_SECC_RUR','LNE', 'Densidad_LNE', 'Razon_LNE_PE', 'TC_LNE_2019', 'Coef_Var_LNE', 'Var_Prop_LNE','Autocorr_LNE']]
#7 indicadores(features)
datos_mun_limpio_f_ind7 = datos_mun_limpio[['NUM_SECC_RUR','LNE', 'Densidad_LNE', 'Razon_LNE_PE', 'TC_LNE_2019', 'Coef_Var_LNE', 'Autocorr_LNE']]
#7 indicadores con transformación log (features)
datos_mun_limpio_f_tf_ind7 = datos_mun_limpio_tf[['NUM_SECC_RUR','LNE', 'Densidad_LNE', 'Razon_LNE_PE', 'TC_LNE_2019', 'Coef_Var_LNE', 'Autocorr_LNE']]
#escenario con 7 indicadores (sin Coef_Var_Prop)
df_pca_results_ind7 = pd.read_csv("C:/Users/miguel.alvarez/Google Drive/INFOTEC/Proyecto/Code-Data/Mun/2_Exploratorio-PCA/Resultados_Mun_PCA_ind7.csv", dtype={'EDO':int,'MUN':int})
#formamos un np-array con las columnas_pca para la sección de métodos de agrupamiento
columnas_7pca = ['CP1', 'CP2', 'CP3','CP4', 'CP5', 'CP6','CP7']
x_pca = df_pca_results_ind7.loc[:, columnas_7pca].values
print(x_pca.shape)
#escenario con 7 indicadores (sin Coef_Var_Prop) con transformacion log
df_pca_results_ind7_tf = pd.read_csv("C:/Users/miguel.alvarez/Google Drive/INFOTEC/Proyecto/Code-Data/Mun/2_Exploratorio-PCA/Resultados_Mun_PCA_ind7_tf.csv", dtype={'EDO':int,'MUN':int})
#formamos un np-array con las columnas_pca para la sección de métodos de agrupamiento
columnas_7pca = ['CP1', 'CP2', 'CP3','CP4', 'CP5', 'CP6','CP7']
x1_pca = df_pca_results_ind7_tf.loc[:, columnas_7pca].values
print(x1_pca.shape)
#escenario con 8 indicadores
df_pca_results_ind8 = pd.read_csv("C:/Users/miguel.alvarez/Google Drive/INFOTEC/Proyecto/Code-Data/Mun/2_Exploratorio-PCA/Resultados_Mun_PCA_ind8.csv", dtype={'EDO':int,'MUN':int})
#formamos un np-array con las columnas_pca para la sección de métodos de agrupamiento
columnas_8pca = ['CP1', 'CP2', 'CP3','CP4', 'CP5', 'CP6','CP7', 'CP8']
x2_pca = df_pca_results_ind8.loc[:, columnas_8pca].values
print(x2_pca.shape)
#escenario con 8 indicadores con transformación log (solo en LNE y Densidad)
df_pca_results_ind8_tf = pd.read_csv("C:/Users/miguel.alvarez/Google Drive/INFOTEC/Proyecto/Code-Data/Mun/2_Exploratorio-PCA/Resultados_Mun_PCA_ind8_tf.csv", dtype={'EDO':int,'MUN':int})
#formamos un np-array con las columnas_pca para la sección de métodos de agrupamiento
columnas_8pca = ['CP1', 'CP2', 'CP3','CP4', 'CP5', 'CP6','CP7', 'CP8']
x3_pca = df_pca_results_ind8_tf.loc[:, columnas_8pca].values
print(x3_pca.shape)
Cálculo de los silhouette_scores para diferentes números de clusters en Kmeans
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_samples, silhouette_score
import matplotlib.cm as cm
#Datos en el espacio de las componentes principales
X=x_pca
#numero de clusters/grupos que serán analizados
range_n_clusters = [2, 3, 4, 5,6,7]
for n_clusters in range_n_clusters:
# Create a subplot with 1 row and 2 columns
fig, (ax1, ax2) = plt.subplots(1, 2)
fig.set_size_inches(18, 7)
# The 1st subplot is the silhouette plot
# The silhouette coefficient can range from -1, 1
ax1.set_xlim([-1, 1])
# The (n_clusters+1)*10 is for inserting blank space between silhouette
# plots of individual clusters, to demarcate them clearly.
ax1.set_ylim([0, len(X) + (n_clusters + 1) * 10])
# Initialize the clusterer with n_clusters value and a random generator
# seed of 0 for reproducibility.
clusterer = KMeans(n_clusters=n_clusters, random_state=0)
cluster_labels = clusterer.fit_predict(X)
# The silhouette_score gives the average value for all the samples.
# This gives a perspective into the density and separation of the formed clusters
silhouette_avg = silhouette_score(X, cluster_labels)
print("For n_clusters =", n_clusters,
"The average silhouette_score is :", silhouette_avg)
# Compute the silhouette scores for each sample
sample_silhouette_values = silhouette_samples(X, cluster_labels)
y_lower = 10
for i in range(n_clusters):
# Aggregate the silhouette scores for samples belonging to
# cluster i, and sort them
ith_cluster_silhouette_values = \
sample_silhouette_values[cluster_labels == i]
ith_cluster_silhouette_values.sort()
size_cluster_i = ith_cluster_silhouette_values.shape[0]
y_upper = y_lower + size_cluster_i
color = cm.nipy_spectral(float(i) / n_clusters)
ax1.fill_betweenx(np.arange(y_lower, y_upper),
0, ith_cluster_silhouette_values,
facecolor=color, edgecolor=color, alpha=0.7)
# Label the silhouette plots with their cluster numbers at the middle
ax1.text(-0.05, y_lower + 0.5 * size_cluster_i, str(i))
# Compute the new y_lower for next plot
y_lower = y_upper + 10 # 10 for the 0 samples
ax1.set_title("Diagrama de silueta por cada grupo.")
ax1.set_xlabel("Coeficiente de silueta")
ax1.set_ylabel("Grupos")
# The vertical line for average silhouette score of all the values
ax1.axvline(x=silhouette_avg, color="red", linestyle="--")
ax1.set_yticks([]) # Clear the yaxis labels / ticks
# 2nd Plot showing the actual clusters formed
colors = cm.nipy_spectral(cluster_labels.astype(float) / n_clusters)
ax2.scatter(X[:, 0], X[:, 1], marker='.', s=30, lw=0, alpha=0.7,
c=colors, edgecolor='k')
# Labeling the clusters
centers = clusterer.cluster_centers_
# Draw white circles at cluster centers
ax2.scatter(centers[:, 0], centers[:, 1], marker='o',
c="white", alpha=1, s=200, edgecolor='k')
for i, c in enumerate(centers):
ax2.scatter(c[0], c[1], marker='$%d$' % i, alpha=1,
s=50, edgecolor='k')
ax2.set_title("TCE en el espacio CP1-CP2")
ax2.set_xlabel("CP1 (ICE principal)")
ax2.set_ylabel("CP2 (segundo ICE)")
plt.suptitle(("Análisis de silueta con K-medias (7 indicadores base). "
"Número de grupos = %d" % n_clusters),
fontsize=14, fontweight='bold')
plt.savefig('Pyplot_silhouette_score_ind7_Kmeans_'+str(n_clusters)+'.png',dpi=600)
Se elige la configuración de 5 clusters (es la tercera configuración con el mayor valor promedio de silueta, pero presenta un agrupamiento adecuado en la proyección bidimensional)
#se obtienen las etiquetas predichas por K-medias para la configuración con el mayor
#valor promedio del silhouete score (n=5)
num_clusters_ind7 = 5
clusterer_K = KMeans(n_clusters=num_clusters_ind7, random_state=0)
clusterer_K_labels = clusterer_K.fit_predict(X)
#se obtienen las etiquetas predichas por Kmeans
y_pred_kmeans = clusterer_K_labels
#se guarda el nparray en un dataframe
y_pred_kmeans = pd.DataFrame(y_pred_kmeans, columns=['TCE_municipal'])
#se transforman las etiquetas numéricas a str
etiquetas_grupos = {0:'G0', 1:'G1', 2:'G2', 3:'G3', 4:'G4', 5:'G5'}
y_pred_kmeans['TCE_municipal']=y_pred_kmeans['TCE_municipal'].apply(lambda x: etiquetas_grupos[x])
#concatenamos los resultados de PCA con las etiquetas de Kmeans
df_pca_results_ind7_kmeans = pd.concat([df_pca_results_ind7, y_pred_kmeans], axis = 1)
#se guardan los resultados en un csv
df_pca_results_ind7_kmeans.to_csv(r'Resultados_Mun_PCA_Kmeans_ind7.csv', index = None)
df_pca_results_ind7_kmeans
Cálculo de los silhouette_scores para diferentes números de clusters en Kmeans
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_samples, silhouette_score
import matplotlib.cm as cm
#Datos en el espacio de las componentes principales
X=x1_pca
#numero de clusters/grupos que serán analizados
range_n_clusters = [2, 3, 4, 5, 6, 7]
for n_clusters in range_n_clusters:
# Create a subplot with 1 row and 2 columns
fig, (ax1, ax2) = plt.subplots(1, 2)
fig.set_size_inches(18, 7)
# The 1st subplot is the silhouette plot
# The silhouette coefficient can range from -1, 1
ax1.set_xlim([-1, 1])
# The (n_clusters+1)*10 is for inserting blank space between silhouette
# plots of individual clusters, to demarcate them clearly.
ax1.set_ylim([0, len(X) + (n_clusters + 1) * 10])
# Initialize the clusterer with n_clusters value and a random generator
# seed of 0 for reproducibility.
clusterer = KMeans(n_clusters=n_clusters, random_state=0)
cluster_labels = clusterer.fit_predict(X)
# The silhouette_score gives the average value for all the samples.
# This gives a perspective into the density and separation of the formed clusters
silhouette_avg = silhouette_score(X, cluster_labels)
print("For n_clusters =", n_clusters,
"The average silhouette_score is :", silhouette_avg)
# Compute the silhouette scores for each sample
sample_silhouette_values = silhouette_samples(X, cluster_labels)
y_lower = 10
for i in range(n_clusters):
# Aggregate the silhouette scores for samples belonging to
# cluster i, and sort them
ith_cluster_silhouette_values = \
sample_silhouette_values[cluster_labels == i]
ith_cluster_silhouette_values.sort()
size_cluster_i = ith_cluster_silhouette_values.shape[0]
y_upper = y_lower + size_cluster_i
color = cm.nipy_spectral(float(i) / n_clusters)
ax1.fill_betweenx(np.arange(y_lower, y_upper),
0, ith_cluster_silhouette_values,
facecolor=color, edgecolor=color, alpha=0.7)
# Label the silhouette plots with their cluster numbers at the middle
ax1.text(-0.05, y_lower + 0.5 * size_cluster_i, str(i))
# Compute the new y_lower for next plot
y_lower = y_upper + 10 # 10 for the 0 samples
ax1.set_title("Diagrama de silueta por cada grupo.")
ax1.set_xlabel("Coeficiente de silueta")
ax1.set_ylabel("Grupos")
# The vertical line for average silhouette score of all the values
ax1.axvline(x=silhouette_avg, color="red", linestyle="--")
ax1.set_yticks([]) # Clear the yaxis labels / ticks
# 2nd Plot showing the actual clusters formed
colors = cm.nipy_spectral(cluster_labels.astype(float) / n_clusters)
ax2.scatter(X[:, 0], X[:, 1], marker='.', s=30, lw=0, alpha=0.7,
c=colors, edgecolor='k')
# Labeling the clusters
centers = clusterer.cluster_centers_
# Draw white circles at cluster centers
ax2.scatter(centers[:, 0], centers[:, 1], marker='o',
c="white", alpha=1, s=200, edgecolor='k')
for i, c in enumerate(centers):
ax2.scatter(c[0], c[1], marker='$%d$' % i, alpha=1,
s=50, edgecolor='k')
ax2.set_title("TCE en el espacio CP1-CP2")
ax2.set_xlabel("CP1 (ICE principal)")
ax2.set_ylabel("CP2 (segundo ICE)")
plt.suptitle(("Análisis de silueta con K-medias (7 indicadores base, con transformación log en LNE y Densidad_LNE). "
"Número de grupos = %d" % n_clusters),
fontsize=14, fontweight='bold')
plt.savefig('Pyplot_silhouette_score_ind7_tf_Kmeans_'+str(n_clusters)+'.png',dpi=600)
Se elige la configuración de 4 clusters (segunda configuración con el mayor valor promedio de silueta, pero con un mejor distribución en la proyección bidimensional).
#se obtienen las etiquetas predichas por K-medias para la configuración con el mejor
#valor promedio del silhouete score, o con la mejor distribucion de los silhouetes (n=4)
num_clusters_ind7_tf = 4
clusterer_K = KMeans(n_clusters=num_clusters_ind7_tf, random_state=0)
clusterer_K_labels = clusterer_K.fit_predict(X)
#se obtienen las etiquetas predichas por Kmeans
y_pred_kmeans = clusterer_K_labels
#se guarda el nparray en un dataframe
y_pred_kmeans = pd.DataFrame(y_pred_kmeans, columns=['TCE_municipal'])
#se transforman las etiquetas numéricas a str
etiquetas_grupos = {0:'G0', 1:'G1', 2:'G2', 3:'G3', 4:'G4', 5:'G5'}
y_pred_kmeans['TCE_municipal']=y_pred_kmeans['TCE_municipal'].apply(lambda x: etiquetas_grupos[x])
#concatenamos los resultados de PCA con las etiquetas de Kmeans
df_pca_results_ind7_tf_kmeans = pd.concat([df_pca_results_ind7_tf, y_pred_kmeans], axis = 1)
#se guardan los resultados en un csv
df_pca_results_ind7_tf_kmeans.to_csv(r'Resultados_Mun_PCA_Kmeans_ind7_tf.csv', index = None)
df_pca_results_ind7_tf_kmeans
Cálculo de los silhouette_scores para diferentes números de clusters en Kmeans
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_samples, silhouette_score
import matplotlib.cm as cm
#Datos en el espacio de las componentes principales
X=x2_pca
#numero de clusters/grupos que serán analizados
range_n_clusters = [2, 3, 4, 5, 6, 7]
for n_clusters in range_n_clusters:
# Create a subplot with 1 row and 2 columns
fig, (ax1, ax2) = plt.subplots(1, 2)
fig.set_size_inches(18, 7)
# The 1st subplot is the silhouette plot
# The silhouette coefficient can range from -1, 1
ax1.set_xlim([-1, 1])
# The (n_clusters+1)*10 is for inserting blank space between silhouette
# plots of individual clusters, to demarcate them clearly.
ax1.set_ylim([0, len(X) + (n_clusters + 1) * 10])
# Initialize the clusterer with n_clusters value and a random generator
# seed of 0 for reproducibility.
clusterer = KMeans(n_clusters=n_clusters, random_state=0)
cluster_labels = clusterer.fit_predict(X)
# The silhouette_score gives the average value for all the samples.
# This gives a perspective into the density and separation of the formed clusters
silhouette_avg = silhouette_score(X, cluster_labels)
print("For n_clusters =", n_clusters,
"The average silhouette_score is :", silhouette_avg)
# Compute the silhouette scores for each sample
sample_silhouette_values = silhouette_samples(X, cluster_labels)
y_lower = 10
for i in range(n_clusters):
# Aggregate the silhouette scores for samples belonging to
# cluster i, and sort them
ith_cluster_silhouette_values = \
sample_silhouette_values[cluster_labels == i]
ith_cluster_silhouette_values.sort()
size_cluster_i = ith_cluster_silhouette_values.shape[0]
y_upper = y_lower + size_cluster_i
color = cm.nipy_spectral(float(i) / n_clusters)
ax1.fill_betweenx(np.arange(y_lower, y_upper),
0, ith_cluster_silhouette_values,
facecolor=color, edgecolor=color, alpha=0.7)
# Label the silhouette plots with their cluster numbers at the middle
ax1.text(-0.05, y_lower + 0.5 * size_cluster_i, str(i))
# Compute the new y_lower for next plot
y_lower = y_upper + 10 # 10 for the 0 samples
ax1.set_title("Diagrama de silueta por cada grupo.")
ax1.set_xlabel("Coeficiente de silueta")
ax1.set_ylabel("Grupos")
# The vertical line for average silhouette score of all the values
ax1.axvline(x=silhouette_avg, color="red", linestyle="--")
ax1.set_yticks([]) # Clear the yaxis labels / ticks
# 2nd Plot showing the actual clusters formed
colors = cm.nipy_spectral(cluster_labels.astype(float) / n_clusters)
ax2.scatter(X[:, 0], X[:, 1], marker='.', s=30, lw=0, alpha=0.7,
c=colors, edgecolor='k')
# Labeling the clusters
centers = clusterer.cluster_centers_
# Draw white circles at cluster centers
ax2.scatter(centers[:, 0], centers[:, 1], marker='o',
c="white", alpha=1, s=200, edgecolor='k')
for i, c in enumerate(centers):
ax2.scatter(c[0], c[1], marker='$%d$' % i, alpha=1,
s=50, edgecolor='k')
ax2.set_title("TCE en el espacio CP1-CP2")
ax2.set_xlabel("CP1 (ICE principal)")
ax2.set_ylabel("CP2 (segundo ICE)")
plt.suptitle(("Análisis de silueta con K-medias (8 indicadores). "
"Número de grupos = %d" % n_clusters),
fontsize=14, fontweight='bold')
plt.savefig('Pyplot_silhouette_score_ind8_Kmeans_'+str(n_clusters)+'.png',dpi=600)
Se elige la configuración de 5 clusters (configuración con el mayor valor promedio de silueta)
#se obtienen las etiquetas predichas por K-medias para la configuración con el mayor
#valor promedio del silhouete score, o la mejor distribución de silhouetes (n=5)
num_clusters_ind8 = 5
clusterer_K = KMeans(n_clusters=num_clusters_ind8, random_state=0)
clusterer_K_labels = clusterer_K.fit_predict(X)
#se obtienen las etiquetas predichas por Kmeans
y_pred_kmeans = clusterer_K_labels
#se guarda el nparray en un dataframe
y_pred_kmeans = pd.DataFrame(y_pred_kmeans, columns=['TCE_municipal'])
#se transforman las etiquetas numéricas a str (adecuacion para preservar color de anteriores graficas)
etiquetas_grupos = {0:'G0', 1:'G1', 2:'G2', 3:'G3', 4:'G4', 5:'G5'}
y_pred_kmeans['TCE_municipal']=y_pred_kmeans['TCE_municipal'].apply(lambda x: etiquetas_grupos[x])
#concatenamos los resultados de PCA con las etiquetas de Kmeans
df_pca_results_ind8_kmeans = pd.concat([df_pca_results_ind8, y_pred_kmeans], axis = 1)
#se guardan los resultados en un csv
df_pca_results_ind8_kmeans.to_csv(r'Resultados_Mun_PCA_Kmeans_ind8.csv', index = None)
df_pca_results_ind8_kmeans
Cálculo de los silhouette_scores para diferentes números de clusters en Kmeans
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_samples, silhouette_score
import matplotlib.cm as cm
#Datos en el espacio de las componentes principales
X=x3_pca
#numero de clusters/grupos que serán analizados
range_n_clusters = [2, 3, 4, 5, 6, 7]
for n_clusters in range_n_clusters:
# Create a subplot with 1 row and 2 columns
fig, (ax1, ax2) = plt.subplots(1, 2)
fig.set_size_inches(18, 7)
# The 1st subplot is the silhouette plot
# The silhouette coefficient can range from -1, 1
ax1.set_xlim([-1, 1])
# The (n_clusters+1)*10 is for inserting blank space between silhouette
# plots of individual clusters, to demarcate them clearly.
ax1.set_ylim([0, len(X) + (n_clusters + 1) * 10])
# Initialize the clusterer with n_clusters value and a random generator
# seed of 0 for reproducibility.
clusterer = KMeans(n_clusters=n_clusters, random_state=0)
cluster_labels = clusterer.fit_predict(X)
# The silhouette_score gives the average value for all the samples.
# This gives a perspective into the density and separation of the formed clusters
silhouette_avg = silhouette_score(X, cluster_labels)
print("For n_clusters =", n_clusters,
"The average silhouette_score is :", silhouette_avg)
# Compute the silhouette scores for each sample
sample_silhouette_values = silhouette_samples(X, cluster_labels)
y_lower = 10
for i in range(n_clusters):
# Aggregate the silhouette scores for samples belonging to
# cluster i, and sort them
ith_cluster_silhouette_values = \
sample_silhouette_values[cluster_labels == i]
ith_cluster_silhouette_values.sort()
size_cluster_i = ith_cluster_silhouette_values.shape[0]
y_upper = y_lower + size_cluster_i
color = cm.nipy_spectral(float(i) / n_clusters)
ax1.fill_betweenx(np.arange(y_lower, y_upper),
0, ith_cluster_silhouette_values,
facecolor=color, edgecolor=color, alpha=0.7)
# Label the silhouette plots with their cluster numbers at the middle
ax1.text(-0.05, y_lower + 0.5 * size_cluster_i, str(i))
# Compute the new y_lower for next plot
y_lower = y_upper + 10 # 10 for the 0 samples
ax1.set_title("Diagrama de silueta por cada grupo.")
ax1.set_xlabel("Coeficiente de silueta")
ax1.set_ylabel("Grupos")
# The vertical line for average silhouette score of all the values
ax1.axvline(x=silhouette_avg, color="red", linestyle="--")
ax1.set_yticks([]) # Clear the yaxis labels / ticks
# 2nd Plot showing the actual clusters formed
colors = cm.nipy_spectral(cluster_labels.astype(float) / n_clusters)
ax2.scatter(X[:, 0], X[:, 1], marker='.', s=30, lw=0, alpha=0.7,
c=colors, edgecolor='k')
# Labeling the clusters
centers = clusterer.cluster_centers_
# Draw white circles at cluster centers
ax2.scatter(centers[:, 0], centers[:, 1], marker='o',
c="white", alpha=1, s=200, edgecolor='k')
for i, c in enumerate(centers):
ax2.scatter(c[0], c[1], marker='$%d$' % i, alpha=1,
s=50, edgecolor='k')
ax2.set_title("TCE en el espacio CP1-CP2")
ax2.set_xlabel("CP1 (ICE principal)")
ax2.set_ylabel("CP2 (segundo ICE)")
plt.suptitle(("Análisis de silueta con K-medias (8 indicadores, con transformación log en LNE y Densidad_LNE). "
"Número de grupos = %d" % n_clusters),
fontsize=14, fontweight='bold')
plt.savefig('Pyplot_silhouette_score_ind8_tf_Kmeans_'+str(n_clusters)+'.png',dpi=600)
Se elige la configuración de 4 clusters (configuración con el mayor valor promedio de silueta)
#se obtienen las etiquetas predichas por K-medias para la configuración con el mayor
#valor promedio del silhouete score (n=4)
num_clusters_ind8_tf = 4
clusterer_K = KMeans(n_clusters=num_clusters_ind8_tf, random_state=0)
clusterer_K_labels = clusterer_K.fit_predict(X)
#se obtienen las etiquetas predichas por Kmeans
y_pred_kmeans = clusterer_K_labels
#se guarda el nparray en un dataframe
y_pred_kmeans = pd.DataFrame(y_pred_kmeans, columns=['TCE_municipal'])
#se transforman las etiquetas numéricas a str (adecuacion para preservar color de anteriores graficas)
etiquetas_grupos = {0:'G0', 1:'G1', 2:'G2', 3:'G3', 4:'G4', 5:'G5'}
y_pred_kmeans['TCE_municipal']=y_pred_kmeans['TCE_municipal'].apply(lambda x: etiquetas_grupos[x])
#concatenamos los resultados de PCA con las etiquetas de Kmeans
df_pca_results_ind8_tf_kmeans = pd.concat([df_pca_results_ind8_tf, y_pred_kmeans], axis = 1)
#se guardan los resultados en un csv
df_pca_results_ind8_tf_kmeans.to_csv(r'Resultados_Mun_PCA_Kmeans_ind8_tf.csv', index = None)
df_pca_results_ind8_tf_kmeans
Se utiliza la última iteración guardada de K-medias para asegurar la reproducibilidad de los resultados (recordando que K-medias es un algoritmo estocástico; y por lo tanto, en cada iteración hay variaciones en la asignación de grupos).
#df_pca_results_ind7_kmeans = pd.read_csv("Resultados_Mun_PCA_Kmeans_ind7.csv", dtype={'EDO':int,'MUN':int,'CP1':float, 'CP2':float, 'CP3':float})
df_pca_results_ind7_kmeans.head()
Gráfica en el espacio CP1, CP2
#Scatter plot (seaborn) CP1 vs CP2 (con clustering k-means)
plt.figure(figsize=(16, 10), dpi= 200, facecolor='w', edgecolor='k')
sns.scatterplot(x="CP1", y="CP2",
data=df_pca_results_ind7_kmeans,
hue="TCE_municipal",
palette=color_dict)
# Set x-axis label
plt.xlabel('CP1 (ICE principal)')
# Set y-axis label
plt.ylabel('CP2 (segundo ICE)')
plt.title('Proyección en CP1-CP2 con tipología (7 indicadores)')
plt.savefig('Pyplot_PCA_Kmeans_ind7.png',dpi=600)
Gráfica en el espacio CP1, CP2, CP3
from matplotlib import pyplot
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.lines import Line2D
#para definir los colores
colores = df_pca_results_ind7_kmeans['TCE_municipal'].apply(lambda x: color_dict[x])
#figura
fig = pyplot.figure(figsize=(16, 10), dpi=600, facecolor='w', edgecolor='k')
ax = Axes3D(fig)
ax.scatter(df_pca_results_ind7_kmeans['CP1'], df_pca_results_ind7_kmeans['CP2'], df_pca_results_ind7_kmeans['CP3'], c=colores,s=15)
# ax.set_xlim3d(-10, 40)
ax.set_ylim3d(-7.5,7.5)
ax.set_zlim3d(-2,8)
ax.set_xlabel('CP1 (ICE principal)')
ax.set_ylabel('CP2 (segundo ICE)')
ax.set_zlabel('CP3 (tercer ICE)')
ax.view_init(elev, azim)
ax.legend(title='TCE_municipal', handles=legend_elements_5, loc='center right',fontsize='x-large')
ax.set_title('Proyección en CP1-CP2-CP3 con tipología (7 indicadores)')
plt.savefig('Pyplot_PCA_3d_Kmeans_ind7.png',dpi=600)
pyplot.show()
Gráfica 3d animada
#3-d plot con plotly
fig = px.scatter_3d(df_pca_results_ind7_kmeans, x='CP1', y='CP2', z='CP3',
color='TCE_municipal',
color_discrete_map={
'G0':'blue',
'G1':'green',
'G2': 'orange',
'G3': 'grey',
'G4': 'red',
'G5': 'magenta'})
fig.update_traces(mode='markers', marker_line_width=1, marker_size=3)
fig.update_layout(scene = dict(
xaxis_title='CP1 (ICE principal)',
yaxis_title='CP2 (segundo ICE)',
zaxis_title='CP3 (tercer ICE)'),
legend_orientation="h")
fig.show()
Se utiliza la última iteración guardada de K-medias para asegurar la reproducibilidad de los resultados (recordando que K-medias es un algoritmo estocástico; y por lo tanto, en cada iteración hay variaciones en la asignación de grupos).
#df_pca_results_ind7_tf_kmeans = pd.read_csv("Resultados_Mun_PCA_Kmeans_ind7_tf.csv", dtype={'EDO':int,'MUN':int,'CP1':float, 'CP2':float, 'CP3':float})
df_pca_results_ind7_tf_kmeans.head()
Gráfica en el espacio CP1, CP2
#Scatter plot (seaborn) CP1 vs CP2 (con clustering k-means)
plt.figure(figsize=(16, 10), dpi= 200, facecolor='w', edgecolor='k')
sns.scatterplot(x="CP1", y="CP2",
data=df_pca_results_ind7_tf_kmeans,
hue="TCE_municipal",
palette=color_dict)
# Set x-axis label
plt.xlabel('CP1 (ICE principal)')
# Set y-axis label
plt.ylabel('CP2 (segundo ICE)')
plt.title('Proyección en CP1-CP2 con tipología (7 indicadores, con transformación log en LNE y Densidad_LNE)')
plt.savefig('Pyplot_PCA_Kmeans_ind7_tf.png',dpi=600)
Gráfica en el espacio CP1, CP2, CP3
from matplotlib import pyplot
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.lines import Line2D
#para definir los colores
colores = df_pca_results_ind7_tf_kmeans['TCE_municipal'].apply(lambda x: color_dict[x])
#figura
fig = pyplot.figure(figsize=(16, 10), dpi=600, facecolor='w', edgecolor='k')
ax = Axes3D(fig)
ax.scatter(df_pca_results_ind7_tf_kmeans['CP1'], df_pca_results_ind7_tf_kmeans['CP2'], df_pca_results_ind7_tf_kmeans['CP3'], c=colores,s=15)
# ax.set_xlim3d(-10, 40)
ax.set_ylim3d(-7.5,7.5)
ax.set_zlim3d(-2,8)
ax.set_xlabel('CP1 (ICE principal)')
ax.set_ylabel('CP2 (segundo ICE)')
ax.set_zlabel('CP3 (tercer ICE)')
ax.view_init(elev, azim)
ax.legend(title='TCE_municipal', handles=legend_elements_4, loc='center right',fontsize='x-large')
ax.set_title('Proyección en CP1-CP2-CP3 con tipología (7 indicadores, con transformación log en LNE y Densidad_LNE)')
plt.savefig('Pyplot_PCA_3d_Kmeans_ind7_tf.png',dpi=600)
pyplot.show()
Gráfica 3d animada
#3-d plot con plotly
fig = px.scatter_3d(df_pca_results_ind7_tf_kmeans, x='CP1', y='CP2', z='CP3',
color='TCE_municipal',
color_discrete_map={
'G0':'blue',
'G1':'green',
'G2': 'orange',
'G3': 'grey',
'G4': 'red',
'G5': 'magenta'})
fig.update_traces(mode='markers', marker_line_width=1, marker_size=3)
fig.update_layout(scene = dict(
xaxis_title='CP1 (ICE principal)',
yaxis_title='CP2 (segundo ICE)',
zaxis_title='CP3 (tercer ICE)'),
legend_orientation="h")
fig.show()
Se utiliza la última iteración guardada de K-medias para asegurar la reproducibilidad de los resultados (recordando que K-medias es un algoritmo estocástico; y por lo tanto, en cada iteración hay variaciones en la asignación de grupos).
#df_pca_results_ind8_kmeans = pd.read_csv("Resultados_Mun_PCA_Kmeans_ind8.csv", dtype={'EDO':int,'MUN':int,'CP1':float, 'CP2':float, 'CP3':float})
df_pca_results_ind8_kmeans.head()
Gráfica en el espacio CP1, CP2
#Scatter plot (seaborn) PC1 vs PC2 (con clustering k-means)
plt.figure(figsize=(16, 10), dpi= 200, facecolor='w', edgecolor='k')
sns.scatterplot(x="CP1", y="CP2",
data=df_pca_results_ind8_kmeans,
hue="TCE_municipal",
palette=color_dict)
# Set x-axis label
plt.xlabel('CP1 (ICE principal)')
# Set y-axis label
plt.ylabel('CP2 (segundo ICE)')
plt.title('Proyección en CP1-CP2 con tipología (8 indicadores)')
plt.savefig('Pyplot_PCA_Kmeans_ind8.png',dpi=600)
Gráfica en el espacio CP1, CP2, CP3
from matplotlib import pyplot
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.lines import Line2D
#para definir los colores
colores = df_pca_results_ind8_kmeans['TCE_municipal'].apply(lambda x: color_dict[x])
#figura
fig = pyplot.figure(figsize=(16, 10), dpi=600, facecolor='w', edgecolor='k')
ax = Axes3D(fig)
ax.scatter(df_pca_results_ind8_kmeans['CP1'], df_pca_results_ind8_kmeans['CP2'], df_pca_results_ind8_kmeans['CP3'], c=colores,s=15)
# ax.set_xlim3d(-10, 40)
ax.set_ylim3d(-9,12)
ax.set_zlim3d(-2,8)
ax.set_xlabel('CP1 (ICE principal)')
ax.set_ylabel('CP2 (segundo ICE)')
ax.set_zlabel('CP3 (tercer ICE)')
ax.view_init(elev, azim)
ax.legend(title='TCE_municipal', handles=legend_elements_5, loc='center right',fontsize='x-large')
ax.set_title('Proyección en CP1-CP2-CP3 con tipología (8 indicadores)')
plt.savefig('Pyplot_PCA_3d_Kmeans_ind8.png',dpi=600)
pyplot.show()
Gráfica 3d animada
#3-d plot con plotly
fig = px.scatter_3d(df_pca_results_ind8_kmeans, x='CP1', y='CP2', z='CP3',
color='TCE_municipal',
color_discrete_map={
'G0':'blue',
'G1':'green',
'G2': 'orange',
'G3': 'grey',
'G4': 'red',
'G5': 'magenta'})
fig.update_traces(mode='markers', marker_line_width=1, marker_size=3)
fig.update_layout(scene = dict(
xaxis_title='CP1 (ICE principal)',
yaxis_title='CP2 (segundo ICE)',
zaxis_title='CP3 (tercer ICE)'),
legend_orientation="h")
fig.show()
Se utiliza la última iteración guardada de K-medias para asegurar la reproducibilidad de los resultados (recordando que K-medias es un algoritmo estocástico; y por lo tanto, en cada iteración hay variaciones en la asignación de grupos).
#df_pca_results_ind8_tf_kmeans = pd.read_csv("Resultados_Mun_PCA_Kmeans_ind8_tf.csv", dtype={'EDO':int,'MUN':int,'CP1':float, 'CP2':float, 'CP3':float})
df_pca_results_ind8_tf_kmeans.head()
Gráfica en el espacio CP1, CP2
#Scatter plot (seaborn) PC1 vs PC2 (con clustering k-means)
plt.figure(figsize=(16, 10), dpi= 200, facecolor='w', edgecolor='k')
sns.scatterplot(x="CP1", y="CP2",
data=df_pca_results_ind8_tf_kmeans,
hue="TCE_municipal",
palette=color_dict)
# Set x-axis label
plt.xlabel('CP1 (ICE principal)')
# Set y-axis label
plt.ylabel('CP2 (segundo ICE)')
plt.title('Proyección en CP1-CP2 con tipología (8 indicadores, con transformación log en LNE y Densidad_LNE)')
plt.savefig('Pyplot_PCA_Kmeans_ind8_tf.png',dpi=600)
Gráfica en el espacio CP1, CP2, CP3
from matplotlib import pyplot
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.lines import Line2D
#para definir los colores
colores = df_pca_results_ind8_tf_kmeans['TCE_municipal'].apply(lambda x: color_dict[x])
#figura
fig = pyplot.figure(figsize=(16, 10), dpi=600, facecolor='w', edgecolor='k')
ax = Axes3D(fig)
ax.scatter(df_pca_results_ind8_tf_kmeans['CP1'], df_pca_results_ind8_tf_kmeans['CP2'], df_pca_results_ind8_tf_kmeans['CP3'], c=colores,s=15)
# ax.set_xlim3d(-10, 40)
ax.set_ylim3d(-7.5,7.5)
ax.set_zlim3d(-2,8)
ax.set_xlabel('CP1 (ICE principal)')
ax.set_ylabel('CP2 (segundo ICE)')
ax.set_zlabel('CP3 (tercer ICE)')
ax.view_init(elev, azim)
ax.legend(title='TCE_municipal', handles=legend_elements_4, loc='center right',fontsize='x-large')
ax.set_title('Proyección en CP1-CP2-CP3 con tipología (8 indicadores, con transformación log en LNE y Densidad_LNE)')
plt.savefig('Pyplot_PCA_3d_Kmeans_ind8_tf.png',dpi=600)
pyplot.show()
Gráfica 3d animada
#3-d plot con plotly
fig = px.scatter_3d(df_pca_results_ind8_tf_kmeans, x='CP1', y='CP2', z='CP3',
color='TCE_municipal',
color_discrete_map={
'G0':'blue',
'G1':'green',
'G2': 'orange',
'G3': 'grey',
'G4': 'red',
'G5': 'magenta'})
fig.update_traces(mode='markers', marker_line_width=1, marker_size=3)
fig.update_layout(scene = dict(
xaxis_title='CP1 (ICE principal)',
yaxis_title='CP2 (segundo ICE)',
zaxis_title='CP3 (tercer ICE)'),
legend_orientation="h")
fig.show()
#unimos los resultados de PCA_Kmeans con los metadatos y los 7 indicadores de los municipios
df_indi_pca_kmeans_ind7=pd.merge(datos_mun_limpio, df_pca_results_ind7_kmeans, on=['EDO','NOMBRE_ESTADO','MUN','NOMBRE_MUNICIPIO'], how='inner')
#renombramos algunas columnas_pca
df_indi_pca_kmeans_ind7=df_indi_pca_kmeans_ind7.rename(columns={"CP1": "CP1 (ICE principal)", "CP2": "CP2 (segundo ICE)", "CP3": "CP3 (tercer ICE)"})
df_indi_pca_kmeans_ind7
#sólo tomamos los indicadores y grupos
df_indi_pca_kmeans_ind7_f = df_indi_pca_kmeans_ind7[['NUM_SECC_RUR','LNE', 'Densidad_LNE', 'Razon_LNE_PE', 'TC_LNE_2019', 'Coef_Var_LNE', 'Autocorr_LNE', 'TCE_municipal']]
#pair-plot (colores en funcion de grupo)
corr3=sns.pairplot(df_indi_pca_kmeans_ind7_f,
hue="TCE_municipal",
palette=color_dict)
corr3.fig.suptitle("Correlograma (7 indicadores base)", y=1.01)
#guardar la pair-plot
corr3.savefig('Pyplot_correlogram_TCE_ind7.png',dpi=600)
Plotgrid de gráficas de caja para cada indicador e índice de complejidad electoral (por grupo)
sns.set(style="whitegrid")
fig, axes = plt.subplots(4, 2, figsize=(16, 20), dpi= 200)
ax = sns.boxplot(x=df_indi_pca_kmeans_ind7["TCE_municipal"], y=df_indi_pca_kmeans_ind7["NUM_SECC_RUR"], palette=color_dict, orient='v',
ax=axes[0, 0])
ax = sns.boxplot(x=df_indi_pca_kmeans_ind7["TCE_municipal"], y=df_indi_pca_kmeans_ind7["LNE"], palette=color_dict, orient='v',
ax=axes[0, 1])
ax = sns.boxplot(x=df_indi_pca_kmeans_ind7["TCE_municipal"], y=df_indi_pca_kmeans_ind7["Densidad_LNE"], palette=color_dict, orient='v',
ax=axes[1, 0])
ax = sns.boxplot(x=df_indi_pca_kmeans_ind7["TCE_municipal"], y=df_indi_pca_kmeans_ind7["Razon_LNE_PE"], palette=color_dict, orient='v',
ax=axes[1, 1])
ax = sns.boxplot(x=df_indi_pca_kmeans_ind7["TCE_municipal"], y=df_indi_pca_kmeans_ind7["TC_LNE_2019"], palette=color_dict, orient='v',
ax=axes[2, 0])
ax = sns.boxplot(x=df_indi_pca_kmeans_ind7["TCE_municipal"], y=df_indi_pca_kmeans_ind7["Coef_Var_LNE"], palette=color_dict, orient='v',
ax=axes[2, 1])
ax = sns.boxplot(x=df_indi_pca_kmeans_ind7["TCE_municipal"], y=df_indi_pca_kmeans_ind7["Autocorr_LNE"], palette=color_dict, orient='v',
ax=axes[3, 0])
ax = sns.boxplot(x=df_indi_pca_kmeans_ind7["TCE_municipal"], y=df_indi_pca_kmeans_ind7["CP1 (ICE principal)"], palette=color_dict, orient='v',
ax=axes[3, 1])
#fig.delaxes(axes[4][1]) #borrar subplot sin usar
plt.subplots_adjust(hspace=0.3) #dar mas espacio vertical
#se guarda la gráfica
plt.savefig('Pyplot_box-plots-grid_TCE_ind7.png',dpi=600)
plt.show()
Gráfica de violín (por grupos, para el indicador "CP1")
plt.figure(figsize=(16, 10), dpi= 300, facecolor='w', edgecolor='k')
sns.violinplot(x=df_indi_pca_kmeans_ind7["TCE_municipal"], y=df_indi_pca_kmeans_ind7["CP1 (ICE principal)"], palette=color_dict);
#se guarda la gráfica
plt.savefig('Pyplot_violin_TCE_ind7.png',dpi=600)
plt.show()
Plotgrid de gráficas de violín para cada indicador e índice de complejidad electoral (por grupo)
sns.set(style="whitegrid")
fig, axes = plt.subplots(4, 2, figsize=(16, 20), dpi= 200)
ax = sns.violinplot(x=df_indi_pca_kmeans_ind7["TCE_municipal"], y=df_indi_pca_kmeans_ind7["NUM_SECC_RUR"], palette=color_dict, orient='v',
ax=axes[0, 0])
ax = sns.violinplot(x=df_indi_pca_kmeans_ind7["TCE_municipal"], y=df_indi_pca_kmeans_ind7["LNE"], palette=color_dict, orient='v',
ax=axes[0, 1])
ax = sns.violinplot(x=df_indi_pca_kmeans_ind7["TCE_municipal"], y=df_indi_pca_kmeans_ind7["Densidad_LNE"], palette=color_dict, orient='v',
ax=axes[1, 0])
ax = sns.violinplot(x=df_indi_pca_kmeans_ind7["TCE_municipal"], y=df_indi_pca_kmeans_ind7["Razon_LNE_PE"], palette=color_dict, orient='v',
ax=axes[1, 1])
ax = sns.violinplot(x=df_indi_pca_kmeans_ind7["TCE_municipal"], y=df_indi_pca_kmeans_ind7["TC_LNE_2019"], palette=color_dict, orient='v',
ax=axes[2, 0])
ax = sns.violinplot(x=df_indi_pca_kmeans_ind7["TCE_municipal"], y=df_indi_pca_kmeans_ind7["Coef_Var_LNE"], palette=color_dict, orient='v',
ax=axes[2, 1])
ax = sns.violinplot(x=df_indi_pca_kmeans_ind7["TCE_municipal"], y=df_indi_pca_kmeans_ind7["Autocorr_LNE"], palette=color_dict, orient='v',
ax=axes[3, 0])
fig.delaxes(axes[3][1]) #borrar subplot sin usar
plt.subplots_adjust(hspace=0.3) #dar mas espacio vertical
#se guarda la gráfica
plt.savefig('Pyplot_violin-plot-grid_TCE_ind7.png',dpi=600)
plt.show()
Etiquetamos los municipios considerados como atípicos en los ICE (considerando la separación por grupos de la tipología, y utilizando la regla intercuartil):
#ejemplo:
df_indi_pca_kmeans_ind7['CP1 (ICE principal)'].quantile(0.25)
def IQsR_clusters(x):
x_0 = x['TCE_municipal'] == 'G0'
x_g0 = x[x_0]
Q1_g0 = x_g0['CP1 (ICE principal)'].quantile(0.25)
Q3_g0 = x_g0['CP1 (ICE principal)'].quantile(0.75)
IQR_pc1_g0 = Q3_g0 - Q1_g0
Q1_pc2_g0 = x_g0['CP2 (segundo ICE)'].quantile(0.25)
Q3_pc2_g0 = x_g0['CP2 (segundo ICE)'].quantile(0.75)
IQR_pc2_g0 = Q3_pc2_g0 - Q1_pc2_g0
Q1_pc3_g0 = x_g0['CP3 (tercer ICE)'].quantile(0.25)
Q3_pc3_g0 = x_g0['CP3 (tercer ICE)'].quantile(0.75)
IQR_pc3_g0 = Q3_pc3_g0 - Q1_pc3_g0
return IQR_pc1_g0+IQR_pc1_g0;
IQsR_clusters(df_indi_pca_kmeans_ind7)
Función para calcular el Q1, Q3 e IQR (calculado por grupos de cluster_Kmeans), y posteriormente clasificar los municipios en tipicos o atipicos en el ICE principal.
def IQR_clusters(x):
x_0 = df_indi_pca_kmeans_ind7['TCE_municipal'] == 'G0'
x_g0 = df_indi_pca_kmeans_ind7[x_0]
Q1_g0 = x_g0['CP1 (ICE principal)'].quantile(0.25)
Q3_g0 = x_g0['CP1 (ICE principal)'].quantile(0.75)
IQR_pc1_g0 = Q3_g0 - Q1_g0
Q1_pc2_g0 = x_g0['CP2 (segundo ICE)'].quantile(0.25)
Q3_pc2_g0 = x_g0['CP2 (segundo ICE)'].quantile(0.75)
IQR_pc2_g0 = Q3_pc2_g0 - Q1_pc2_g0
Q1_pc3_g0 = x_g0['CP3 (tercer ICE)'].quantile(0.25)
Q3_pc3_g0 = x_g0['CP3 (tercer ICE)'].quantile(0.75)
IQR_pc3_g0 = Q3_pc3_g0 - Q1_pc3_g0
x_1 = df_indi_pca_kmeans_ind7['TCE_municipal'] == 'G1'
x_g1 = df_indi_pca_kmeans_ind7[x_1]
Q1_g1 = x_g1['CP1 (ICE principal)'].quantile(0.25)
Q3_g1 = x_g1['CP1 (ICE principal)'].quantile(0.75)
IQR_pc1_g1 = Q3_g1 - Q1_g1
Q1_pc2_g1 = x_g1['CP2 (segundo ICE)'].quantile(0.25)
Q3_pc2_g1 = x_g1['CP2 (segundo ICE)'].quantile(0.75)
IQR_pc2_g1 = Q3_pc2_g1 - Q1_pc2_g1
Q1_pc3_g1 = x_g1['CP3 (tercer ICE)'].quantile(0.25)
Q3_pc3_g1 = x_g1['CP3 (tercer ICE)'].quantile(0.75)
IQR_pc3_g1 = Q3_pc3_g1 - Q1_pc3_g1
x_2 = df_indi_pca_kmeans_ind7['TCE_municipal'] == 'G2'
x_g2 = df_indi_pca_kmeans_ind7[x_2]
Q1_g2 = x_g2['CP1 (ICE principal)'].quantile(0.25)
Q3_g2 = x_g2['CP1 (ICE principal)'].quantile(0.75)
IQR_pc1_g2 = Q3_g2 - Q1_g2
Q1_pc2_g2 = x_g2['CP2 (segundo ICE)'].quantile(0.25)
Q3_pc2_g2 = x_g2['CP2 (segundo ICE)'].quantile(0.75)
IQR_pc2_g2 = Q3_pc2_g2 - Q1_pc2_g2
Q1_pc3_g2 = x_g2['CP3 (tercer ICE)'].quantile(0.25)
Q3_pc3_g2 = x_g2['CP3 (tercer ICE)'].quantile(0.75)
IQR_pc3_g2 = Q3_pc3_g2 - Q1_pc3_g2
x_3 = df_indi_pca_kmeans_ind7['TCE_municipal'] == 'G3'
x_g3 = df_indi_pca_kmeans_ind7[x_3]
Q1_g3 = x_g3['CP1 (ICE principal)'].quantile(0.25)
Q3_g3 = x_g3['CP1 (ICE principal)'].quantile(0.75)
IQR_pc1_g3 = Q3_g3 - Q1_g3
Q1_pc2_g3 = x_g3['CP2 (segundo ICE)'].quantile(0.25)
Q3_pc2_g3 = x_g3['CP2 (segundo ICE)'].quantile(0.75)
IQR_pc2_g3 = Q3_pc2_g3 - Q1_pc2_g3
Q1_pc3_g3 = x_g3['CP3 (tercer ICE)'].quantile(0.25)
Q3_pc3_g3 = x_g3['CP3 (tercer ICE)'].quantile(0.75)
IQR_pc3_g3 = Q3_pc3_g3 - Q1_pc3_g3
x_4 = df_indi_pca_kmeans_ind7['TCE_municipal'] == 'G4'
x_g4 = df_indi_pca_kmeans_ind7[x_4]
Q1_g4 = x_g4['CP1 (ICE principal)'].quantile(0.25)
Q3_g4 = x_g4['CP1 (ICE principal)'].quantile(0.75)
IQR_pc1_g4 = Q3_g4 - Q1_g4
Q1_pc2_g4 = x_g4['CP2 (segundo ICE)'].quantile(0.25)
Q3_pc2_g4 = x_g4['CP2 (segundo ICE)'].quantile(0.75)
IQR_pc2_g4 = Q3_pc2_g4 - Q1_pc2_g4
Q1_pc3_g4 = x_g4['CP3 (tercer ICE)'].quantile(0.25)
Q3_pc3_g4 = x_g4['CP3 (tercer ICE)'].quantile(0.75)
IQR_pc3_g4 = Q3_pc3_g4 - Q1_pc3_g4
# x_5 = df_indi_pca_kmeans_ind7['TCE_municipal'] == 'G5'
# x_g5 = df_indi_pca_kmeans_ind7[x_5]
# Q1_g5 = x_g5['CP1 (ICE principal)'].quantile(0.25)
# Q3_g5 = x_g5['CP1 (ICE principal)'].quantile(0.75)
# IQR_pc1_g5 = Q3_g5 - Q1_g5
# Q1_pc2_g5 = x_g5['CP2 (segundo ICE)'].quantile(0.25)
# Q3_pc2_g5 = x_g5['CP2 (segundo ICE)'].quantile(0.75)
# IQR_pc2_g5 = Q3_pc2_g5 - Q1_pc2_g5
# Q1_pc3_g5 = x_g5['CP3 (tercer ICE)'].quantile(0.25)
# Q3_pc3_g5 = x_g5['CP3 (tercer ICE)'].quantile(0.75)
# IQR_pc3_g5 = Q3_pc3_g5 - Q1_pc3_g5
if (x['TCE_municipal'] == 'G0'):
if (x['CP1 (ICE principal)'] < Q1_g0-1.5*IQR_pc1_g0) or (x['CP1 (ICE principal)'] > Q3_g0+1.5*IQR_pc1_g0):
return 'Atípica en ICE principal'
elif (x['CP2 (segundo ICE)'] < Q1_pc2_g0-1.5*IQR_pc2_g0) or (x['CP2 (segundo ICE)'] > Q3_pc2_g0+1.5*IQR_pc2_g0):
return 'Atípica en segundo ICE'
elif (x['CP3 (tercer ICE)'] < Q1_pc3_g0-1.5*IQR_pc3_g0) or (x['CP3 (tercer ICE)'] > Q3_pc3_g0+1.5*IQR_pc3_g0):
return 'Atípica en tercer ICE'
else:
return 'Tipica'
elif (x['TCE_municipal'] == 'G1'):
if (x['CP1 (ICE principal)'] < Q1_g1-1.5*IQR_pc1_g1) or (x['CP1 (ICE principal)'] > Q3_g1+1.5*IQR_pc1_g1):
return 'Atípica en ICE principal'
elif (x['CP2 (segundo ICE)'] < Q1_pc2_g1-1.5*IQR_pc2_g1) or (x['CP2 (segundo ICE)'] > Q3_pc2_g1+1.5*IQR_pc2_g1):
return 'Atípica en segundo ICE'
elif (x['CP3 (tercer ICE)'] < Q1_pc3_g1-1.5*IQR_pc3_g1) or (x['CP3 (tercer ICE)'] > Q3_pc3_g1+1.5*IQR_pc3_g1):
return 'Atípica en tercer ICE'
else:
return 'Tipica'
elif (x['TCE_municipal'] == 'G2'):
if (x['CP1 (ICE principal)'] < Q1_g2-1.5*IQR_pc1_g2) or (x['CP1 (ICE principal)'] > Q3_g2+1.5*IQR_pc1_g2):
return 'Atípica en ICE principal'
elif (x['CP2 (segundo ICE)'] < Q1_pc2_g2-1.5*IQR_pc2_g2) or (x['CP2 (segundo ICE)'] > Q3_pc2_g2+1.5*IQR_pc2_g2):
return 'Atípica en segundo ICE'
elif (x['CP3 (tercer ICE)'] < Q1_pc3_g2-1.5*IQR_pc3_g2) or (x['CP3 (tercer ICE)'] > Q3_pc3_g2+1.5*IQR_pc3_g2):
return 'Atípica en tercer ICE'
else:
return 'Tipica'
elif (x['TCE_municipal'] == 'G3'):
if (x['CP1 (ICE principal)'] < Q1_g3-1.5*IQR_pc1_g3) or (x['CP1 (ICE principal)'] > Q3_g3+1.5*IQR_pc1_g3):
return 'Atípica en ICE principal'
elif (x['CP2 (segundo ICE)'] < Q1_pc2_g3-1.5*IQR_pc2_g3) or (x['CP2 (segundo ICE)'] > Q3_pc2_g3+1.5*IQR_pc2_g3):
return 'Atípica en segundo ICE'
elif (x['CP3 (tercer ICE)'] < Q1_pc3_g3-1.5*IQR_pc3_g3) or (x['CP3 (tercer ICE)'] > Q3_pc3_g3+1.5*IQR_pc3_g3):
return 'Atípica en tercer ICE'
else:
return 'Tipica'
elif (x['TCE_municipal'] == 'G4'):
if (x['CP1 (ICE principal)'] < Q1_g4-1.5*IQR_pc1_g4) or (x['CP1 (ICE principal)'] > Q3_g4+1.5*IQR_pc1_g4):
return 'Atípica en ICE principal'
elif (x['CP2 (segundo ICE)'] < Q1_pc2_g4-1.5*IQR_pc2_g4) or (x['CP2 (segundo ICE)'] > Q3_pc2_g4+1.5*IQR_pc2_g4):
return 'Atípica en segundo ICE'
elif (x['CP3 (tercer ICE)'] < Q1_pc3_g4-1.5*IQR_pc3_g4) or (x['CP3 (tercer ICE)'] > Q3_pc3_g4+1.5*IQR_pc3_g4):
return 'Atípica en tercer ICE'
else:
return 'Tipica'
# elif (x['TCE_municipal'] == 'G5'):
# if (x['CP1 (ICE principal)'] < Q1_g5-1.5*IQR_pc1_g5) or (x['CP1 (ICE principal)'] > Q3_g5+1.5*IQR_pc1_g5):
# return 'Atípica en ICE principal'
# elif (x['CP2 (segundo ICE)'] < Q1_pc2_g5-1.5*IQR_pc2_g5) or (x['CP2 (segundo ICE)'] > Q3_pc2_g5+1.5*IQR_pc2_g5):
# return 'Atípica en segundo ICE'
# elif (x['CP3 (tercer ICE)'] < Q1_pc3_g5-1.5*IQR_pc3_g5) or (x['CP3 (tercer ICE)'] > Q3_pc3_g5+1.5*IQR_pc3_g5):
# return 'Atípica en tercer ICE'
# else:
# return 'Tipica'
else:
return 'nan'
#se aplica la función al último df con los resultados:
df_indi_pca_kmeans_ind7['Atipicidad'] = df_indi_pca_kmeans_ind7.apply(IQR_clusters, axis = 1)
#se muestra el dataframe:
df_indi_pca_kmeans_ind7
#para verificar, imprimimos los valores únicos en la columna Atipicidad.
df_indi_pca_kmeans_ind7.Atipicidad.unique()
#imprimimos la frecuencia de los valores únicos en Atipicidad
df_indi_pca_kmeans_ind7['Atipicidad'].value_counts()
#imprimimos el número de municipios por grupo de la tipología.
df_indi_pca_kmeans_ind7['TCE_municipal'].value_counts()
#se guardan los resultados en un csv
df_indi_pca_kmeans_ind7.to_csv(r'Resultados_Mun_Indic_PCA_Kmeans_Atip_ind7.csv', index = None)
#unimos los resultados de PCA_Kmeans con los metadatos y los 7 indicadores de los municipios
df_indi_pca_kmeans_ind7_tf=pd.merge(datos_mun_limpio_tf, df_pca_results_ind7_tf_kmeans, on=['EDO','NOMBRE_ESTADO','MUN','NOMBRE_MUNICIPIO'], how='inner')
#renombramos algunas columnas_pca
df_indi_pca_kmeans_ind7_tf=df_indi_pca_kmeans_ind7_tf.rename(columns={"CP1": "CP1 (ICE principal)",
"CP2": "CP2 (segundo ICE)",
"CP3": "CP3 (tercer ICE)",
"LNE": "log(LNE)",
"Densidad_LNE": "log(Densidad_LNE)"})
df_indi_pca_kmeans_ind7_tf
#sólo tomamos los indicadores y grupos
df_indi_pca_kmeans_ind7_tf_f = df_indi_pca_kmeans_ind7_tf[['NUM_SECC_RUR','log(LNE)', 'log(Densidad_LNE)', 'Razon_LNE_PE', 'TC_LNE_2019', 'Coef_Var_LNE', 'Autocorr_LNE', 'TCE_municipal']]
#pair-plot (colores en funcion de grupo)
corr3_tf=sns.pairplot(df_indi_pca_kmeans_ind7_tf_f,
hue="TCE_municipal",
palette=color_dict)
corr3_tf.fig.suptitle("Correlograma (7 indicadores base, con transformación log en LNE y Densidad_LNE)", y=1.01)
#guardar la pair-plot
corr3_tf.savefig('Pyplot_correlogram_TCE_ind7_tf.png',dpi=600)
Plotgrid de gráficas de caja para cada indicador e índice de complejidad electoral (por grupo)
sns.set(style="whitegrid")
fig, axes = plt.subplots(4, 2, figsize=(16, 20), dpi= 200)
ax = sns.boxplot(x=df_indi_pca_kmeans_ind7_tf["TCE_municipal"], y=df_indi_pca_kmeans_ind7_tf["NUM_SECC_RUR"], palette=color_dict, orient='v',
ax=axes[0, 0])
ax = sns.boxplot(x=df_indi_pca_kmeans_ind7_tf["TCE_municipal"], y=df_indi_pca_kmeans_ind7_tf["log(LNE)"], palette=color_dict, orient='v',
ax=axes[0, 1])
ax = sns.boxplot(x=df_indi_pca_kmeans_ind7_tf["TCE_municipal"], y=df_indi_pca_kmeans_ind7_tf["log(Densidad_LNE)"], palette=color_dict, orient='v',
ax=axes[1, 0])
ax = sns.boxplot(x=df_indi_pca_kmeans_ind7_tf["TCE_municipal"], y=df_indi_pca_kmeans_ind7_tf["Razon_LNE_PE"], palette=color_dict, orient='v',
ax=axes[1, 1])
ax = sns.boxplot(x=df_indi_pca_kmeans_ind7_tf["TCE_municipal"], y=df_indi_pca_kmeans_ind7_tf["TC_LNE_2019"], palette=color_dict, orient='v',
ax=axes[2, 0])
ax = sns.boxplot(x=df_indi_pca_kmeans_ind7_tf["TCE_municipal"], y=df_indi_pca_kmeans_ind7_tf["Coef_Var_LNE"], palette=color_dict, orient='v',
ax=axes[2, 1])
ax = sns.boxplot(x=df_indi_pca_kmeans_ind7_tf["TCE_municipal"], y=df_indi_pca_kmeans_ind7_tf["Autocorr_LNE"], palette=color_dict, orient='v',
ax=axes[3, 0])
ax = sns.boxplot(x=df_indi_pca_kmeans_ind7_tf["TCE_municipal"], y=df_indi_pca_kmeans_ind7_tf["CP1 (ICE principal)"], palette=color_dict, orient='v',
ax=axes[3, 1])
#fig.delaxes(axes[4][1]) #borrar subplot sin usar
plt.subplots_adjust(hspace=0.3) #dar mas espacio vertical
#se guarda la gráfica
plt.savefig('Pyplot_box-plots-grid_TCE_ind7_tf.png',dpi=600)
plt.show()
Gráfica de violín (por grupos, para el indicador "CP1")
plt.figure(figsize=(16, 10), dpi= 300, facecolor='w', edgecolor='k')
sns.violinplot(x=df_indi_pca_kmeans_ind7_tf["TCE_municipal"], y=df_indi_pca_kmeans_ind7_tf["CP1 (ICE principal)"], palette=color_dict);
#se guarda la gráfica
plt.savefig('Pyplot_violin_TCE_ind7_tf.png',dpi=600)
plt.show()
Plotgrid de gráficas de violín para cada indicador e índice de complejidad electoral (por grupo)
sns.set(style="whitegrid")
fig, axes = plt.subplots(4, 2, figsize=(16, 20), dpi= 200)
ax = sns.violinplot(x=df_indi_pca_kmeans_ind7_tf["TCE_municipal"], y=df_indi_pca_kmeans_ind7_tf["NUM_SECC_RUR"], palette=color_dict, orient='v',
ax=axes[0, 0])
ax = sns.violinplot(x=df_indi_pca_kmeans_ind7_tf["TCE_municipal"], y=df_indi_pca_kmeans_ind7_tf["log(LNE)"], palette=color_dict, orient='v',
ax=axes[0, 1])
ax = sns.violinplot(x=df_indi_pca_kmeans_ind7_tf["TCE_municipal"], y=df_indi_pca_kmeans_ind7_tf["log(Densidad_LNE)"], palette=color_dict, orient='v',
ax=axes[1, 0])
ax = sns.violinplot(x=df_indi_pca_kmeans_ind7_tf["TCE_municipal"], y=df_indi_pca_kmeans_ind7_tf["Razon_LNE_PE"], palette=color_dict, orient='v',
ax=axes[1, 1])
ax = sns.violinplot(x=df_indi_pca_kmeans_ind7_tf["TCE_municipal"], y=df_indi_pca_kmeans_ind7_tf["TC_LNE_2019"], palette=color_dict, orient='v',
ax=axes[2, 0])
ax = sns.violinplot(x=df_indi_pca_kmeans_ind7_tf["TCE_municipal"], y=df_indi_pca_kmeans_ind7_tf["Coef_Var_LNE"], palette=color_dict, orient='v',
ax=axes[2, 1])
ax = sns.violinplot(x=df_indi_pca_kmeans_ind7_tf["TCE_municipal"], y=df_indi_pca_kmeans_ind7_tf["Autocorr_LNE"], palette=color_dict, orient='v',
ax=axes[3, 0])
fig.delaxes(axes[3][1]) #borrar subplot sin usar
plt.subplots_adjust(hspace=0.3) #dar mas espacio vertical
#se guarda la gráfica
plt.savefig('Pyplot_violin-plot-grid_TCE_ind7_tf.png',dpi=600)
plt.show()
Etiquetamos los municipios considerados como atípicos en los ICE (considerando la separación por grupos de la tipología, y utilizando la regla intercuartil):
def IQsR_clusters(x):
x_0 = x['TCE_municipal'] == 'G0'
x_g0 = x[x_0]
Q1_g0 = x_g0['CP1 (ICE principal)'].quantile(0.25)
Q3_g0 = x_g0['CP1 (ICE principal)'].quantile(0.75)
IQR_pc1_g0 = Q3_g0 - Q1_g0
Q1_pc2_g0 = x_g0['CP2 (segundo ICE)'].quantile(0.25)
Q3_pc2_g0 = x_g0['CP2 (segundo ICE)'].quantile(0.75)
IQR_pc2_g0 = Q3_pc2_g0 - Q1_pc2_g0
Q1_pc3_g0 = x_g0['CP3 (tercer ICE)'].quantile(0.25)
Q3_pc3_g0 = x_g0['CP3 (tercer ICE)'].quantile(0.75)
IQR_pc3_g0 = Q3_pc3_g0 - Q1_pc3_g0
return IQR_pc1_g0+IQR_pc1_g0;
IQsR_clusters(df_indi_pca_kmeans_ind7_tf)
Función para calcular el Q1, Q3 e IQR (calculado por grupos de cluster_Kmeans), y posteriormente clasificar los municipios en tipicos o atipicos en el ICE principal, en el segundo ICE, o en el tercer ICE:
def IQR_clusters_tf(x):
x_0 = df_indi_pca_kmeans_ind7_tf['TCE_municipal'] == 'G0'
x_g0 = df_indi_pca_kmeans_ind7_tf[x_0]
Q1_g0 = x_g0['CP1 (ICE principal)'].quantile(0.25)
Q3_g0 = x_g0['CP1 (ICE principal)'].quantile(0.75)
IQR_pc1_g0 = Q3_g0 - Q1_g0
Q1_pc2_g0 = x_g0['CP2 (segundo ICE)'].quantile(0.25)
Q3_pc2_g0 = x_g0['CP2 (segundo ICE)'].quantile(0.75)
IQR_pc2_g0 = Q3_pc2_g0 - Q1_pc2_g0
Q1_pc3_g0 = x_g0['CP3 (tercer ICE)'].quantile(0.25)
Q3_pc3_g0 = x_g0['CP3 (tercer ICE)'].quantile(0.75)
IQR_pc3_g0 = Q3_pc3_g0 - Q1_pc3_g0
x_1 = df_indi_pca_kmeans_ind7_tf['TCE_municipal'] == 'G1'
x_g1 = df_indi_pca_kmeans_ind7_tf[x_1]
Q1_g1 = x_g1['CP1 (ICE principal)'].quantile(0.25)
Q3_g1 = x_g1['CP1 (ICE principal)'].quantile(0.75)
IQR_pc1_g1 = Q3_g1 - Q1_g1
Q1_pc2_g1 = x_g1['CP2 (segundo ICE)'].quantile(0.25)
Q3_pc2_g1 = x_g1['CP2 (segundo ICE)'].quantile(0.75)
IQR_pc2_g1 = Q3_pc2_g1 - Q1_pc2_g1
Q1_pc3_g1 = x_g1['CP3 (tercer ICE)'].quantile(0.25)
Q3_pc3_g1 = x_g1['CP3 (tercer ICE)'].quantile(0.75)
IQR_pc3_g1 = Q3_pc3_g1 - Q1_pc3_g1
x_2 = df_indi_pca_kmeans_ind7_tf['TCE_municipal'] == 'G2'
x_g2 = df_indi_pca_kmeans_ind7_tf[x_2]
Q1_g2 = x_g2['CP1 (ICE principal)'].quantile(0.25)
Q3_g2 = x_g2['CP1 (ICE principal)'].quantile(0.75)
IQR_pc1_g2 = Q3_g2 - Q1_g2
Q1_pc2_g2 = x_g2['CP2 (segundo ICE)'].quantile(0.25)
Q3_pc2_g2 = x_g2['CP2 (segundo ICE)'].quantile(0.75)
IQR_pc2_g2 = Q3_pc2_g2 - Q1_pc2_g2
Q1_pc3_g2 = x_g2['CP3 (tercer ICE)'].quantile(0.25)
Q3_pc3_g2 = x_g2['CP3 (tercer ICE)'].quantile(0.75)
IQR_pc3_g2 = Q3_pc3_g2 - Q1_pc3_g2
x_3 = df_indi_pca_kmeans_ind7_tf['TCE_municipal'] == 'G3'
x_g3 = df_indi_pca_kmeans_ind7_tf[x_3]
Q1_g3 = x_g3['CP1 (ICE principal)'].quantile(0.25)
Q3_g3 = x_g3['CP1 (ICE principal)'].quantile(0.75)
IQR_pc1_g3 = Q3_g3 - Q1_g3
Q1_pc2_g3 = x_g3['CP2 (segundo ICE)'].quantile(0.25)
Q3_pc2_g3 = x_g3['CP2 (segundo ICE)'].quantile(0.75)
IQR_pc2_g3 = Q3_pc2_g3 - Q1_pc2_g3
Q1_pc3_g3 = x_g3['CP3 (tercer ICE)'].quantile(0.25)
Q3_pc3_g3 = x_g3['CP3 (tercer ICE)'].quantile(0.75)
IQR_pc3_g3 = Q3_pc3_g3 - Q1_pc3_g3
# x_4 = df_indi_pca_kmeans_ind7_tf['TCE_municipal'] == 'G4'
# x_g4 = df_indi_pca_kmeans_ind7_tf[x_4]
# Q1_g4 = x_g4['CP1 (ICE principal)'].quantile(0.25)
# Q3_g4 = x_g4['CP1 (ICE principal)'].quantile(0.75)
# IQR_pc1_g4 = Q3_g4 - Q1_g4
# Q1_pc2_g4 = x_g4['CP2 (segundo ICE)'].quantile(0.25)
# Q3_pc2_g4 = x_g4['CP2 (segundo ICE)'].quantile(0.75)
# IQR_pc2_g4 = Q3_pc2_g4 - Q1_pc2_g4
# Q1_pc3_g4 = x_g4['CP3 (tercer ICE)'].quantile(0.25)
# Q3_pc3_g4 = x_g4['CP3 (tercer ICE)'].quantile(0.75)
# IQR_pc3_g4 = Q3_pc3_g4 - Q1_pc3_g4
# x_5 = df_indi_pca_kmeans_ind7_tf['TCE_municipal'] == 'G5'
# x_g5 = df_indi_pca_kmeans_ind7_tf[x_5]
# Q1_g5 = x_g5['CP1 (ICE principal)'].quantile(0.25)
# Q3_g5 = x_g5['CP1 (ICE principal)'].quantile(0.75)
# IQR_pc1_g5 = Q3_g5 - Q1_g5
# Q1_pc2_g5 = x_g5['CP2 (segundo ICE)'].quantile(0.25)
# Q3_pc2_g5 = x_g5['CP2 (segundo ICE)'].quantile(0.75)
# IQR_pc2_g5 = Q3_pc2_g5 - Q1_pc2_g5
# Q1_pc3_g5 = x_g5['CP3 (tercer ICE)'].quantile(0.25)
# Q3_pc3_g5 = x_g5['CP3 (tercer ICE)'].quantile(0.75)
# IQR_pc3_g5 = Q3_pc3_g5 - Q1_pc3_g5
if (x['TCE_municipal'] == 'G0'):
if (x['CP1 (ICE principal)'] < Q1_g0-1.5*IQR_pc1_g0) or (x['CP1 (ICE principal)'] > Q3_g0+1.5*IQR_pc1_g0):
return 'Atípica en ICE principal'
elif (x['CP2 (segundo ICE)'] < Q1_pc2_g0-1.5*IQR_pc2_g0) or (x['CP2 (segundo ICE)'] > Q3_pc2_g0+1.5*IQR_pc2_g0):
return 'Atípica en segundo ICE'
elif (x['CP3 (tercer ICE)'] < Q1_pc3_g0-1.5*IQR_pc3_g0) or (x['CP3 (tercer ICE)'] > Q3_pc3_g0+1.5*IQR_pc3_g0):
return 'Atípica en tercer ICE'
else:
return 'Tipica'
elif (x['TCE_municipal'] == 'G1'):
if (x['CP1 (ICE principal)'] < Q1_g1-1.5*IQR_pc1_g1) or (x['CP1 (ICE principal)'] > Q3_g1+1.5*IQR_pc1_g1):
return 'Atípica en ICE principal'
elif (x['CP2 (segundo ICE)'] < Q1_pc2_g1-1.5*IQR_pc2_g1) or (x['CP2 (segundo ICE)'] > Q3_pc2_g1+1.5*IQR_pc2_g1):
return 'Atípica en segundo ICE'
elif (x['CP3 (tercer ICE)'] < Q1_pc3_g1-1.5*IQR_pc3_g1) or (x['CP3 (tercer ICE)'] > Q3_pc3_g1+1.5*IQR_pc3_g1):
return 'Atípica en tercer ICE'
else:
return 'Tipica'
elif (x['TCE_municipal'] == 'G2'):
if (x['CP1 (ICE principal)'] < Q1_g2-1.5*IQR_pc1_g2) or (x['CP1 (ICE principal)'] > Q3_g2+1.5*IQR_pc1_g2):
return 'Atípica en ICE principal'
elif (x['CP2 (segundo ICE)'] < Q1_pc2_g2-1.5*IQR_pc2_g2) or (x['CP2 (segundo ICE)'] > Q3_pc2_g2+1.5*IQR_pc2_g2):
return 'Atípica en segundo ICE'
elif (x['CP3 (tercer ICE)'] < Q1_pc3_g2-1.5*IQR_pc3_g2) or (x['CP3 (tercer ICE)'] > Q3_pc3_g2+1.5*IQR_pc3_g2):
return 'Atípica en tercer ICE'
else:
return 'Tipica'
elif (x['TCE_municipal'] == 'G3'):
if (x['CP1 (ICE principal)'] < Q1_g3-1.5*IQR_pc1_g3) or (x['CP1 (ICE principal)'] > Q3_g3+1.5*IQR_pc1_g3):
return 'Atípica en ICE principal'
elif (x['CP2 (segundo ICE)'] < Q1_pc2_g3-1.5*IQR_pc2_g3) or (x['CP2 (segundo ICE)'] > Q3_pc2_g3+1.5*IQR_pc2_g3):
return 'Atípica en segundo ICE'
elif (x['CP3 (tercer ICE)'] < Q1_pc3_g3-1.5*IQR_pc3_g3) or (x['CP3 (tercer ICE)'] > Q3_pc3_g3+1.5*IQR_pc3_g3):
return 'Atípica en tercer ICE'
else:
return 'Tipica'
# elif (x['TCE_municipal'] == 'G4'):
# if (x['CP1 (ICE principal)'] < Q1_g4-1.5*IQR_pc1_g4) or (x['CP1 (ICE principal)'] > Q3_g4+1.5*IQR_pc1_g4):
# return 'Atípica en ICE principal'
# elif (x['CP2 (segundo ICE)'] < Q1_pc2_g4-1.5*IQR_pc2_g4) or (x['CP2 (segundo ICE)'] > Q3_pc2_g4+1.5*IQR_pc2_g4):
# return 'Atípica en segundo ICE'
# elif (x['CP3 (tercer ICE)'] < Q1_pc3_g4-1.5*IQR_pc3_g4) or (x['CP3 (tercer ICE)'] > Q3_pc3_g4+1.5*IQR_pc3_g4):
# return 'Atípica en tercer ICE'
# else:
# return 'Tipica'
# elif (x['TCE_municipal'] == 'G5'):
# if (x['CP1 (ICE principal)'] < Q1_g5-1.5*IQR_pc1_g5) or (x['CP1 (ICE principal)'] > Q3_g5+1.5*IQR_pc1_g5):
# return 'Atípica en ICE principal'
# elif (x['CP2 (segundo ICE)'] < Q1_pc2_g5-1.5*IQR_pc2_g5) or (x['CP2 (segundo ICE)'] > Q3_pc2_g5+1.5*IQR_pc2_g5):
# return 'Atípica en segundo ICE'
# elif (x['CP3 (tercer ICE)'] < Q1_pc3_g5-1.5*IQR_pc3_g5) or (x['CP3 (tercer ICE)'] > Q3_pc3_g5+1.5*IQR_pc3_g5):
# return 'Atípica en tercer ICE'
# else:
# return 'Tipica'
else:
return 'nan'
#se aplica la función al último df con los resultados:
df_indi_pca_kmeans_ind7_tf['Atipicidad'] = df_indi_pca_kmeans_ind7_tf.apply(IQR_clusters_tf, axis = 1)
#se muestra el dataframe:
df_indi_pca_kmeans_ind7_tf
#para verificar, imprimimos los valores únicos en la columna Atipicidad.
df_indi_pca_kmeans_ind7_tf.Atipicidad.unique()
#imprimimos la frecuencia de los valores únicos en Atipicidad
df_indi_pca_kmeans_ind7_tf['Atipicidad'].value_counts()
#imprimimos el número de municipios por grupo de la tipología.
df_indi_pca_kmeans_ind7_tf['TCE_municipal'].value_counts()
#se guardan los resultados en un csv
df_indi_pca_kmeans_ind7_tf.to_csv(r'Resultados_Mun_Indic_PCA_Kmeans_Atip_ind7_tf.csv', index = None)
#unimos los resultados de PCA_Kmeans con los metadatos y los 8 indicadores de los municipios
df_indi_pca_kmeans_ind8=pd.merge(datos_mun_limpio, df_pca_results_ind8_kmeans, on=['EDO','NOMBRE_ESTADO','MUN','NOMBRE_MUNICIPIO'], how='inner')
#renombramos algunas columnas_pca
df_indi_pca_kmeans_ind8=df_indi_pca_kmeans_ind8.rename(columns={"CP1": "CP1 (ICE principal)", "CP2": "CP2 (segundo ICE)", "CP3": "CP3 (tercer ICE)"})
df_indi_pca_kmeans_ind8
#sólo tomamos los indicadores y grupos
df_indi_pca_kmeans_ind8_f = df_indi_pca_kmeans_ind8[['NUM_SECC_RUR','LNE', 'Densidad_LNE', 'Razon_LNE_PE', 'TC_LNE_2019', 'Coef_Var_LNE', 'Var_Prop_LNE', 'Autocorr_LNE', 'TCE_municipal']]
#pair-plot (colores en funcion de grupo)
corr4=sns.pairplot(df_indi_pca_kmeans_ind8_f,
hue="TCE_municipal",
palette=color_dict)
corr4.fig.suptitle("Correlograma (8 indicadores base)", y=1.01)
#guardar la pair-plot
corr4.savefig('Pyplot_correlogram_TCE_ind8.png',dpi=600)
Plotgrid de gráficas de caja para cada indicador e índice de complejidad electoral (por grupo)
sns.set(style="whitegrid")
fig, axes = plt.subplots(5, 2, figsize=(16, 20), dpi= 200)
ax = sns.boxplot(x=df_indi_pca_kmeans_ind8["TCE_municipal"], y=df_indi_pca_kmeans_ind8["NUM_SECC_RUR"], palette=color_dict, orient='v',
ax=axes[0, 0])
ax = sns.boxplot(x=df_indi_pca_kmeans_ind8["TCE_municipal"], y=df_indi_pca_kmeans_ind8["LNE"], palette=color_dict, orient='v',
ax=axes[0, 1])
ax = sns.boxplot(x=df_indi_pca_kmeans_ind8["TCE_municipal"], y=df_indi_pca_kmeans_ind8["Densidad_LNE"], palette=color_dict, orient='v',
ax=axes[1, 0])
ax = sns.boxplot(x=df_indi_pca_kmeans_ind8["TCE_municipal"], y=df_indi_pca_kmeans_ind8["Razon_LNE_PE"], palette=color_dict, orient='v',
ax=axes[1, 1])
ax = sns.boxplot(x=df_indi_pca_kmeans_ind8["TCE_municipal"], y=df_indi_pca_kmeans_ind8["TC_LNE_2019"], palette=color_dict, orient='v',
ax=axes[2, 0])
ax = sns.boxplot(x=df_indi_pca_kmeans_ind8["TCE_municipal"], y=df_indi_pca_kmeans_ind8["Coef_Var_LNE"], palette=color_dict, orient='v',
ax=axes[2, 1])
ax = sns.boxplot(x=df_indi_pca_kmeans_ind8["TCE_municipal"], y=df_indi_pca_kmeans_ind8["Var_Prop_LNE"], palette=color_dict, orient='v',
ax=axes[3, 0])
ax = sns.boxplot(x=df_indi_pca_kmeans_ind8["TCE_municipal"], y=df_indi_pca_kmeans_ind8["Autocorr_LNE"], palette=color_dict, orient='v',
ax=axes[3, 1])
ax = sns.boxplot(x=df_indi_pca_kmeans_ind8["TCE_municipal"], y=df_indi_pca_kmeans_ind8["CP1 (ICE principal)"], palette=color_dict, orient='v',
ax=axes[4, 0])
fig.delaxes(axes[4][1]) #borrar subplot sin usar
plt.subplots_adjust(hspace=0.3) #dar mas espacio vertical
#se guarda la gráfica
plt.savefig('Pyplot_box-plots-grid_TCE_ind8.png',dpi=600)
plt.show()
Gráfica de violín (por grupos, para el indicador "CP1")
plt.figure(figsize=(16, 10), dpi= 300, facecolor='w', edgecolor='k')
sns.violinplot(x=df_indi_pca_kmeans_ind8["TCE_municipal"], y=df_indi_pca_kmeans_ind8["CP1 (ICE principal)"], palette=color_dict);
#se guarda la gráfica
plt.savefig('Pyplot_violin_TCE_ind8.png',dpi=600)
plt.show()
Plotgrid de gráficas de violín para cada indicador e índice de complejidad electoral (por grupo)
sns.set(style="whitegrid")
fig, axes = plt.subplots(4, 2, figsize=(16, 20), dpi= 200)
ax = sns.violinplot(x=df_indi_pca_kmeans_ind8["TCE_municipal"], y=df_indi_pca_kmeans_ind8["NUM_SECC_RUR"], palette=color_dict, orient='v',
ax=axes[0, 0])
ax = sns.violinplot(x=df_indi_pca_kmeans_ind8["TCE_municipal"], y=df_indi_pca_kmeans_ind8["LNE"], palette=color_dict, orient='v',
ax=axes[0, 1])
ax = sns.violinplot(x=df_indi_pca_kmeans_ind8["TCE_municipal"], y=df_indi_pca_kmeans_ind8["Densidad_LNE"], palette=color_dict, orient='v',
ax=axes[1, 0])
ax = sns.violinplot(x=df_indi_pca_kmeans_ind8["TCE_municipal"], y=df_indi_pca_kmeans_ind8["Razon_LNE_PE"], palette=color_dict, orient='v',
ax=axes[1, 1])
ax = sns.violinplot(x=df_indi_pca_kmeans_ind8["TCE_municipal"], y=df_indi_pca_kmeans_ind8["TC_LNE_2019"], palette=color_dict, orient='v',
ax=axes[2, 0])
ax = sns.violinplot(x=df_indi_pca_kmeans_ind8["TCE_municipal"], y=df_indi_pca_kmeans_ind8["Coef_Var_LNE"], palette=color_dict, orient='v',
ax=axes[2, 1])
ax = sns.violinplot(x=df_indi_pca_kmeans_ind8["TCE_municipal"], y=df_indi_pca_kmeans_ind8["Var_Prop_LNE"], palette=color_dict, orient='v',
ax=axes[3, 0])
ax = sns.violinplot(x=df_indi_pca_kmeans_ind8["TCE_municipal"], y=df_indi_pca_kmeans_ind8["Autocorr_LNE"], palette=color_dict, orient='v',
ax=axes[3, 1])
#fig.delaxes(axes[5][1]) #borrar subplot sin usar
plt.subplots_adjust(hspace=0.3) #dar mas espacio vertical
#se guarda la gráfica
plt.savefig('Pyplot_violin-plot-grid_TCE_ind8.png',dpi=600)
plt.show()
Etiquetamos los municipios considerados como atípicos en los ICE (considerando la separación por grupos de la tipología, y utilizando la regla intercuartil):
#ejemplo:
df_indi_pca_kmeans_ind8['CP1 (ICE principal)'].quantile(0.25)
def IQsR_clusters(x):
x_0 = x['TCE_municipal'] == 'G0'
x_g0 = x[x_0]
Q1_g0 = x_g0['CP1 (ICE principal)'].quantile(0.25)
Q3_g0 = x_g0['CP1 (ICE principal)'].quantile(0.75)
IQR_pc1_g0 = Q3_g0 - Q1_g0
Q1_pc2_g0 = x_g0['CP2 (segundo ICE)'].quantile(0.25)
Q3_pc2_g0 = x_g0['CP2 (segundo ICE)'].quantile(0.75)
IQR_pc2_g0 = Q3_pc2_g0 - Q1_pc2_g0
Q1_pc3_g0 = x_g0['CP3 (tercer ICE)'].quantile(0.25)
Q3_pc3_g0 = x_g0['CP3 (tercer ICE)'].quantile(0.75)
IQR_pc3_g0 = Q3_pc3_g0 - Q1_pc3_g0
return IQR_pc1_g0+IQR_pc1_g0;
IQsR_clusters(df_indi_pca_kmeans_ind8)
Función para calcular el Q1, Q3 e IQR (calculado por grupos de cluster_Kmeans), y posteriormente clasificar los municipios en tipicos o atipicos en el ICE principal.
def IQR_clusters(x):
x_0 = df_indi_pca_kmeans_ind8['TCE_municipal'] == 'G0'
x_g0 = df_indi_pca_kmeans_ind8[x_0]
Q1_g0 = x_g0['CP1 (ICE principal)'].quantile(0.25)
Q3_g0 = x_g0['CP1 (ICE principal)'].quantile(0.75)
IQR_pc1_g0 = Q3_g0 - Q1_g0
Q1_pc2_g0 = x_g0['CP2 (segundo ICE)'].quantile(0.25)
Q3_pc2_g0 = x_g0['CP2 (segundo ICE)'].quantile(0.75)
IQR_pc2_g0 = Q3_pc2_g0 - Q1_pc2_g0
Q1_pc3_g0 = x_g0['CP3 (tercer ICE)'].quantile(0.25)
Q3_pc3_g0 = x_g0['CP3 (tercer ICE)'].quantile(0.75)
IQR_pc3_g0 = Q3_pc3_g0 - Q1_pc3_g0
x_1 = df_indi_pca_kmeans_ind8['TCE_municipal'] == 'G1'
x_g1 = df_indi_pca_kmeans_ind8[x_1]
Q1_g1 = x_g1['CP1 (ICE principal)'].quantile(0.25)
Q3_g1 = x_g1['CP1 (ICE principal)'].quantile(0.75)
IQR_pc1_g1 = Q3_g1 - Q1_g1
Q1_pc2_g1 = x_g1['CP2 (segundo ICE)'].quantile(0.25)
Q3_pc2_g1 = x_g1['CP2 (segundo ICE)'].quantile(0.75)
IQR_pc2_g1 = Q3_pc2_g1 - Q1_pc2_g1
Q1_pc3_g1 = x_g1['CP3 (tercer ICE)'].quantile(0.25)
Q3_pc3_g1 = x_g1['CP3 (tercer ICE)'].quantile(0.75)
IQR_pc3_g1 = Q3_pc3_g1 - Q1_pc3_g1
x_2 = df_indi_pca_kmeans_ind8['TCE_municipal'] == 'G2'
x_g2 = df_indi_pca_kmeans_ind8[x_2]
Q1_g2 = x_g2['CP1 (ICE principal)'].quantile(0.25)
Q3_g2 = x_g2['CP1 (ICE principal)'].quantile(0.75)
IQR_pc1_g2 = Q3_g2 - Q1_g2
Q1_pc2_g2 = x_g2['CP2 (segundo ICE)'].quantile(0.25)
Q3_pc2_g2 = x_g2['CP2 (segundo ICE)'].quantile(0.75)
IQR_pc2_g2 = Q3_pc2_g2 - Q1_pc2_g2
Q1_pc3_g2 = x_g2['CP3 (tercer ICE)'].quantile(0.25)
Q3_pc3_g2 = x_g2['CP3 (tercer ICE)'].quantile(0.75)
IQR_pc3_g2 = Q3_pc3_g2 - Q1_pc3_g2
x_3 = df_indi_pca_kmeans_ind8['TCE_municipal'] == 'G3'
x_g3 = df_indi_pca_kmeans_ind8[x_3]
Q1_g3 = x_g3['CP1 (ICE principal)'].quantile(0.25)
Q3_g3 = x_g3['CP1 (ICE principal)'].quantile(0.75)
IQR_pc1_g3 = Q3_g3 - Q1_g3
Q1_pc2_g3 = x_g3['CP2 (segundo ICE)'].quantile(0.25)
Q3_pc2_g3 = x_g3['CP2 (segundo ICE)'].quantile(0.75)
IQR_pc2_g3 = Q3_pc2_g3 - Q1_pc2_g3
Q1_pc3_g3 = x_g3['CP3 (tercer ICE)'].quantile(0.25)
Q3_pc3_g3 = x_g3['CP3 (tercer ICE)'].quantile(0.75)
IQR_pc3_g3 = Q3_pc3_g3 - Q1_pc3_g3
x_4 = df_indi_pca_kmeans_ind8['TCE_municipal'] == 'G4'
x_g4 = df_indi_pca_kmeans_ind8[x_4]
Q1_g4 = x_g4['CP1 (ICE principal)'].quantile(0.25)
Q3_g4 = x_g4['CP1 (ICE principal)'].quantile(0.75)
IQR_pc1_g4 = Q3_g4 - Q1_g4
Q1_pc2_g4 = x_g4['CP2 (segundo ICE)'].quantile(0.25)
Q3_pc2_g4 = x_g4['CP2 (segundo ICE)'].quantile(0.75)
IQR_pc2_g4 = Q3_pc2_g4 - Q1_pc2_g4
Q1_pc3_g4 = x_g4['CP3 (tercer ICE)'].quantile(0.25)
Q3_pc3_g4 = x_g4['CP3 (tercer ICE)'].quantile(0.75)
IQR_pc3_g4 = Q3_pc3_g4 - Q1_pc3_g4
# x_5 = df_indi_pca_kmeans_ind8['TCE_municipal'] == 'G5'
# x_g5 = df_indi_pca_kmeans_ind8[x_5]
# Q1_g5 = x_g5['CP1 (ICE principal)'].quantile(0.25)
# Q3_g5 = x_g5['CP1 (ICE principal)'].quantile(0.75)
# IQR_pc1_g5 = Q3_g5 - Q1_g5
# Q1_pc2_g5 = x_g5['CP2 (segundo ICE)'].quantile(0.25)
# Q3_pc2_g5 = x_g5['CP2 (segundo ICE)'].quantile(0.75)
# IQR_pc2_g5 = Q3_pc2_g5 - Q1_pc2_g5
# Q1_pc3_g5 = x_g5['CP3 (tercer ICE)'].quantile(0.25)
# Q3_pc3_g5 = x_g5['CP3 (tercer ICE)'].quantile(0.75)
# IQR_pc3_g5 = Q3_pc3_g5 - Q1_pc3_g5
if (x['TCE_municipal'] == 'G0'):
if (x['CP1 (ICE principal)'] < Q1_g0-1.5*IQR_pc1_g0) or (x['CP1 (ICE principal)'] > Q3_g0+1.5*IQR_pc1_g0):
return 'Atípica en ICE principal'
elif (x['CP2 (segundo ICE)'] < Q1_pc2_g0-1.5*IQR_pc2_g0) or (x['CP2 (segundo ICE)'] > Q3_pc2_g0+1.5*IQR_pc2_g0):
return 'Atípica en segundo ICE'
elif (x['CP3 (tercer ICE)'] < Q1_pc3_g0-1.5*IQR_pc3_g0) or (x['CP3 (tercer ICE)'] > Q3_pc3_g0+1.5*IQR_pc3_g0):
return 'Atípica en tercer ICE'
else:
return 'Tipica'
elif (x['TCE_municipal'] == 'G1'):
if (x['CP1 (ICE principal)'] < Q1_g1-1.5*IQR_pc1_g1) or (x['CP1 (ICE principal)'] > Q3_g1+1.5*IQR_pc1_g1):
return 'Atípica en ICE principal'
elif (x['CP2 (segundo ICE)'] < Q1_pc2_g1-1.5*IQR_pc2_g1) or (x['CP2 (segundo ICE)'] > Q3_pc2_g1+1.5*IQR_pc2_g1):
return 'Atípica en segundo ICE'
elif (x['CP3 (tercer ICE)'] < Q1_pc3_g1-1.5*IQR_pc3_g1) or (x['CP3 (tercer ICE)'] > Q3_pc3_g1+1.5*IQR_pc3_g1):
return 'Atípica en tercer ICE'
else:
return 'Tipica'
elif (x['TCE_municipal'] == 'G2'):
if (x['CP1 (ICE principal)'] < Q1_g2-1.5*IQR_pc1_g2) or (x['CP1 (ICE principal)'] > Q3_g2+1.5*IQR_pc1_g2):
return 'Atípica en ICE principal'
elif (x['CP2 (segundo ICE)'] < Q1_pc2_g2-1.5*IQR_pc2_g2) or (x['CP2 (segundo ICE)'] > Q3_pc2_g2+1.5*IQR_pc2_g2):
return 'Atípica en segundo ICE'
elif (x['CP3 (tercer ICE)'] < Q1_pc3_g2-1.5*IQR_pc3_g2) or (x['CP3 (tercer ICE)'] > Q3_pc3_g2+1.5*IQR_pc3_g2):
return 'Atípica en tercer ICE'
else:
return 'Tipica'
elif (x['TCE_municipal'] == 'G3'):
if (x['CP1 (ICE principal)'] < Q1_g3-1.5*IQR_pc1_g3) or (x['CP1 (ICE principal)'] > Q3_g3+1.5*IQR_pc1_g3):
return 'Atípica en ICE principal'
elif (x['CP2 (segundo ICE)'] < Q1_pc2_g3-1.5*IQR_pc2_g3) or (x['CP2 (segundo ICE)'] > Q3_pc2_g3+1.5*IQR_pc2_g3):
return 'Atípica en segundo ICE'
elif (x['CP3 (tercer ICE)'] < Q1_pc3_g3-1.5*IQR_pc3_g3) or (x['CP3 (tercer ICE)'] > Q3_pc3_g3+1.5*IQR_pc3_g3):
return 'Atípica en tercer ICE'
else:
return 'Tipica'
elif (x['TCE_municipal'] == 'G4'):
if (x['CP1 (ICE principal)'] < Q1_g4-1.5*IQR_pc1_g4) or (x['CP1 (ICE principal)'] > Q3_g4+1.5*IQR_pc1_g4):
return 'Atípica en ICE principal'
elif (x['CP2 (segundo ICE)'] < Q1_pc2_g4-1.5*IQR_pc2_g4) or (x['CP2 (segundo ICE)'] > Q3_pc2_g4+1.5*IQR_pc2_g4):
return 'Atípica en segundo ICE'
elif (x['CP3 (tercer ICE)'] < Q1_pc3_g4-1.5*IQR_pc3_g4) or (x['CP3 (tercer ICE)'] > Q3_pc3_g4+1.5*IQR_pc3_g4):
return 'Atípica en tercer ICE'
else:
return 'Tipica'
# elif (x['TCE_municipal'] == 'G5'):
# if (x['CP1 (ICE principal)'] < Q1_g5-1.5*IQR_pc1_g5) or (x['CP1 (ICE principal)'] > Q3_g5+1.5*IQR_pc1_g5):
# return 'Atípica en ICE principal'
# elif (x['CP2 (segundo ICE)'] < Q1_pc2_g5-1.5*IQR_pc2_g5) or (x['CP2 (segundo ICE)'] > Q3_pc2_g5+1.5*IQR_pc2_g5):
# return 'Atípica en segundo ICE'
# elif (x['CP3 (tercer ICE)'] < Q1_pc3_g5-1.5*IQR_pc3_g5) or (x['CP3 (tercer ICE)'] > Q3_pc3_g5+1.5*IQR_pc3_g5):
# return 'Atípica en tercer ICE'
# else:
# return 'Tipica'
else:
return 'nan'
#se aplica la función al último df con los resultados:
df_indi_pca_kmeans_ind8['Atipicidad'] = df_indi_pca_kmeans_ind8.apply(IQR_clusters, axis = 1)
#se muestra el dataframe:
df_indi_pca_kmeans_ind8
#para verificar, imprimimos los valores únicos en la columna Atipicidad.
df_indi_pca_kmeans_ind8.Atipicidad.unique()
#imprimimos la frecuencia de los valores únicos en Atipicidad
df_indi_pca_kmeans_ind8['Atipicidad'].value_counts()
#imprimimos el número de municipios por grupo de la tipología.
df_indi_pca_kmeans_ind8['TCE_municipal'].value_counts()
#se guardan los resultados en un csv
df_indi_pca_kmeans_ind8.to_csv(r'Resultados_Mun_Indic_PCA_Kmeans_Atip_ind8.csv', index = None)
#unimos los resultados de PCA_Kmeans con los metadatos y los 8 indicadores de los municipios
df_indi_pca_kmeans_ind8_tf=pd.merge(datos_mun_limpio_tf, df_pca_results_ind8_tf_kmeans, on=['EDO','NOMBRE_ESTADO','MUN','NOMBRE_MUNICIPIO'], how='inner')
#renombramos algunas columnas_pca
df_indi_pca_kmeans_ind8_tf=df_indi_pca_kmeans_ind8_tf.rename(columns={"CP1": "CP1 (ICE principal)",
"CP2": "CP2 (segundo ICE)",
"CP3": "CP3 (tercer ICE)",
"LNE": "log(LNE)",
"Densidad_LNE": "log(Densidad_LNE)"})
df_indi_pca_kmeans_ind8_tf
#sólo tomamos los indicadores y grupos
df_indi_pca_kmeans_ind8_tf_f = df_indi_pca_kmeans_ind8_tf[['NUM_SECC_RUR','log(LNE)', 'log(Densidad_LNE)', 'Razon_LNE_PE', 'TC_LNE_2019', 'Coef_Var_LNE', 'Var_Prop_LNE', 'Autocorr_LNE', 'TCE_municipal']]
#pair-plot (colores en funcion de grupo)
corr4_tf=sns.pairplot(df_indi_pca_kmeans_ind8_tf_f,
hue="TCE_municipal",
palette=color_dict)
corr4_tf.fig.suptitle("Correlograma (8 indicadores base, con transformación log en LNE y Densidad_LNE)", y=1.01)
#guardar la pair-plot
corr4_tf.savefig('Pyplot_correlogram_TCE_ind8_tf.png',dpi=600)
Plotgrid de gráficas de caja para cada indicador e índice de complejidad electoral (por grupo)
sns.set(style="whitegrid")
fig, axes = plt.subplots(5, 2, figsize=(16, 20), dpi= 200)
ax = sns.boxplot(x=df_indi_pca_kmeans_ind8_tf["TCE_municipal"], y=df_indi_pca_kmeans_ind8_tf["NUM_SECC_RUR"], palette=color_dict, orient='v',
ax=axes[0, 0])
ax = sns.boxplot(x=df_indi_pca_kmeans_ind8_tf["TCE_municipal"], y=df_indi_pca_kmeans_ind8_tf["log(LNE)"], palette=color_dict, orient='v',
ax=axes[0, 1])
ax = sns.boxplot(x=df_indi_pca_kmeans_ind8_tf["TCE_municipal"], y=df_indi_pca_kmeans_ind8_tf["log(Densidad_LNE)"], palette=color_dict, orient='v',
ax=axes[1, 0])
ax = sns.boxplot(x=df_indi_pca_kmeans_ind8_tf["TCE_municipal"], y=df_indi_pca_kmeans_ind8_tf["Razon_LNE_PE"], palette=color_dict, orient='v',
ax=axes[1, 1])
ax = sns.boxplot(x=df_indi_pca_kmeans_ind8_tf["TCE_municipal"], y=df_indi_pca_kmeans_ind8_tf["TC_LNE_2019"], palette=color_dict, orient='v',
ax=axes[2, 0])
ax = sns.boxplot(x=df_indi_pca_kmeans_ind8_tf["TCE_municipal"], y=df_indi_pca_kmeans_ind8_tf["Coef_Var_LNE"], palette=color_dict, orient='v',
ax=axes[2, 1])
ax = sns.boxplot(x=df_indi_pca_kmeans_ind8_tf["TCE_municipal"], y=df_indi_pca_kmeans_ind8_tf["Var_Prop_LNE"], palette=color_dict, orient='v',
ax=axes[3, 0])
ax = sns.boxplot(x=df_indi_pca_kmeans_ind8_tf["TCE_municipal"], y=df_indi_pca_kmeans_ind8_tf["Autocorr_LNE"], palette=color_dict, orient='v',
ax=axes[3, 1])
ax = sns.boxplot(x=df_indi_pca_kmeans_ind8_tf["TCE_municipal"], y=df_indi_pca_kmeans_ind8_tf["CP1 (ICE principal)"], palette=color_dict, orient='v',
ax=axes[4, 0])
fig.delaxes(axes[4][1]) #borrar subplot sin usar
plt.subplots_adjust(hspace=0.3) #dar mas espacio vertical
#se guarda la gráfica
plt.savefig('Pyplot_box-plots-grid_TCE_ind8_tf.png',dpi=600)
plt.show()
Gráfica de violín (por grupos, para el indicador "CP1")
plt.figure(figsize=(16, 10), dpi= 300, facecolor='w', edgecolor='k')
sns.violinplot(x=df_indi_pca_kmeans_ind8_tf["TCE_municipal"], y=df_indi_pca_kmeans_ind8_tf["CP1 (ICE principal)"], palette=color_dict);
#se guarda la gráfica
plt.savefig('Pyplot_violin_TCE_ind8_tf.png',dpi=600)
plt.show()
Plotgrid de gráficas de violín para cada indicador e índice de complejidad electoral (por grupo)
sns.set(style="whitegrid")
fig, axes = plt.subplots(4, 2, figsize=(16, 20), dpi= 200)
ax = sns.violinplot(x=df_indi_pca_kmeans_ind8_tf["TCE_municipal"], y=df_indi_pca_kmeans_ind8_tf["NUM_SECC_RUR"], palette=color_dict, orient='v',
ax=axes[0, 0])
ax = sns.violinplot(x=df_indi_pca_kmeans_ind8_tf["TCE_municipal"], y=df_indi_pca_kmeans_ind8_tf["log(LNE)"], palette=color_dict, orient='v',
ax=axes[0, 1])
ax = sns.violinplot(x=df_indi_pca_kmeans_ind8_tf["TCE_municipal"], y=df_indi_pca_kmeans_ind8_tf["log(Densidad_LNE)"], palette=color_dict, orient='v',
ax=axes[1, 0])
ax = sns.violinplot(x=df_indi_pca_kmeans_ind8_tf["TCE_municipal"], y=df_indi_pca_kmeans_ind8_tf["Razon_LNE_PE"], palette=color_dict, orient='v',
ax=axes[1, 1])
ax = sns.violinplot(x=df_indi_pca_kmeans_ind8_tf["TCE_municipal"], y=df_indi_pca_kmeans_ind8_tf["TC_LNE_2019"], palette=color_dict, orient='v',
ax=axes[2, 0])
ax = sns.violinplot(x=df_indi_pca_kmeans_ind8_tf["TCE_municipal"], y=df_indi_pca_kmeans_ind8_tf["Coef_Var_LNE"], palette=color_dict, orient='v',
ax=axes[2, 1])
ax = sns.violinplot(x=df_indi_pca_kmeans_ind8_tf["TCE_municipal"], y=df_indi_pca_kmeans_ind8_tf["Var_Prop_LNE"], palette=color_dict, orient='v',
ax=axes[3, 0])
ax = sns.violinplot(x=df_indi_pca_kmeans_ind8_tf["TCE_municipal"], y=df_indi_pca_kmeans_ind8_tf["Autocorr_LNE"], palette=color_dict, orient='v',
ax=axes[3, 1])
#fig.delaxes(axes[5][1]) #borrar subplot sin usar
plt.subplots_adjust(hspace=0.3) #dar mas espacio vertical
#se guarda la gráfica
plt.savefig('Pyplot_violin-plot-grid_TCE_ind8_tf.png',dpi=600)
plt.show()
Etiquetamos los municipios considerados como atípicos en los ICE (considerando la separación por grupos de la tipología, y utilizando la regla intercuartil):
def IQsR_clusters(x):
x_0 = x['TCE_municipal'] == 'G0'
x_g0 = x[x_0]
Q1_g0 = x_g0['CP1 (ICE principal)'].quantile(0.25)
Q3_g0 = x_g0['CP1 (ICE principal)'].quantile(0.75)
IQR_pc1_g0 = Q3_g0 - Q1_g0
Q1_pc2_g0 = x_g0['CP2 (segundo ICE)'].quantile(0.25)
Q3_pc2_g0 = x_g0['CP2 (segundo ICE)'].quantile(0.75)
IQR_pc2_g0 = Q3_pc2_g0 - Q1_pc2_g0
Q1_pc3_g0 = x_g0['CP3 (tercer ICE)'].quantile(0.25)
Q3_pc3_g0 = x_g0['CP3 (tercer ICE)'].quantile(0.75)
IQR_pc3_g0 = Q3_pc3_g0 - Q1_pc3_g0
return IQR_pc1_g0+IQR_pc1_g0;
IQsR_clusters(df_indi_pca_kmeans_ind8_tf)
Función para calcular el Q1, Q3 e IQR (calculado por grupos de cluster_Kmeans), y posteriormente clasificar los municipios en tipicos o atipicos en el ICE principal, en el segundo ICE, o en el tercer ICE:
def IQR_clusters_tf(x):
x_0 = df_indi_pca_kmeans_ind8_tf['TCE_municipal'] == 'G0'
x_g0 = df_indi_pca_kmeans_ind8_tf[x_0]
Q1_g0 = x_g0['CP1 (ICE principal)'].quantile(0.25)
Q3_g0 = x_g0['CP1 (ICE principal)'].quantile(0.75)
IQR_pc1_g0 = Q3_g0 - Q1_g0
Q1_pc2_g0 = x_g0['CP2 (segundo ICE)'].quantile(0.25)
Q3_pc2_g0 = x_g0['CP2 (segundo ICE)'].quantile(0.75)
IQR_pc2_g0 = Q3_pc2_g0 - Q1_pc2_g0
Q1_pc3_g0 = x_g0['CP3 (tercer ICE)'].quantile(0.25)
Q3_pc3_g0 = x_g0['CP3 (tercer ICE)'].quantile(0.75)
IQR_pc3_g0 = Q3_pc3_g0 - Q1_pc3_g0
x_1 = df_indi_pca_kmeans_ind8_tf['TCE_municipal'] == 'G1'
x_g1 = df_indi_pca_kmeans_ind8_tf[x_1]
Q1_g1 = x_g1['CP1 (ICE principal)'].quantile(0.25)
Q3_g1 = x_g1['CP1 (ICE principal)'].quantile(0.75)
IQR_pc1_g1 = Q3_g1 - Q1_g1
Q1_pc2_g1 = x_g1['CP2 (segundo ICE)'].quantile(0.25)
Q3_pc2_g1 = x_g1['CP2 (segundo ICE)'].quantile(0.75)
IQR_pc2_g1 = Q3_pc2_g1 - Q1_pc2_g1
Q1_pc3_g1 = x_g1['CP3 (tercer ICE)'].quantile(0.25)
Q3_pc3_g1 = x_g1['CP3 (tercer ICE)'].quantile(0.75)
IQR_pc3_g1 = Q3_pc3_g1 - Q1_pc3_g1
x_2 = df_indi_pca_kmeans_ind8_tf['TCE_municipal'] == 'G2'
x_g2 = df_indi_pca_kmeans_ind8_tf[x_2]
Q1_g2 = x_g2['CP1 (ICE principal)'].quantile(0.25)
Q3_g2 = x_g2['CP1 (ICE principal)'].quantile(0.75)
IQR_pc1_g2 = Q3_g2 - Q1_g2
Q1_pc2_g2 = x_g2['CP2 (segundo ICE)'].quantile(0.25)
Q3_pc2_g2 = x_g2['CP2 (segundo ICE)'].quantile(0.75)
IQR_pc2_g2 = Q3_pc2_g2 - Q1_pc2_g2
Q1_pc3_g2 = x_g2['CP3 (tercer ICE)'].quantile(0.25)
Q3_pc3_g2 = x_g2['CP3 (tercer ICE)'].quantile(0.75)
IQR_pc3_g2 = Q3_pc3_g2 - Q1_pc3_g2
x_3 = df_indi_pca_kmeans_ind8_tf['TCE_municipal'] == 'G3'
x_g3 = df_indi_pca_kmeans_ind8_tf[x_3]
Q1_g3 = x_g3['CP1 (ICE principal)'].quantile(0.25)
Q3_g3 = x_g3['CP1 (ICE principal)'].quantile(0.75)
IQR_pc1_g3 = Q3_g3 - Q1_g3
Q1_pc2_g3 = x_g3['CP2 (segundo ICE)'].quantile(0.25)
Q3_pc2_g3 = x_g3['CP2 (segundo ICE)'].quantile(0.75)
IQR_pc2_g3 = Q3_pc2_g3 - Q1_pc2_g3
Q1_pc3_g3 = x_g3['CP3 (tercer ICE)'].quantile(0.25)
Q3_pc3_g3 = x_g3['CP3 (tercer ICE)'].quantile(0.75)
IQR_pc3_g3 = Q3_pc3_g3 - Q1_pc3_g3
# x_4 = df_indi_pca_kmeans_ind8_tf['TCE_municipal'] == 'G4'
# x_g4 = df_indi_pca_kmeans_ind8_tf[x_4]
# Q1_g4 = x_g4['CP1 (ICE principal)'].quantile(0.25)
# Q3_g4 = x_g4['CP1 (ICE principal)'].quantile(0.75)
# IQR_pc1_g4 = Q3_g4 - Q1_g4
# Q1_pc2_g4 = x_g4['CP2 (segundo ICE)'].quantile(0.25)
# Q3_pc2_g4 = x_g4['CP2 (segundo ICE)'].quantile(0.75)
# IQR_pc2_g4 = Q3_pc2_g4 - Q1_pc2_g4
# Q1_pc3_g4 = x_g4['CP3 (tercer ICE)'].quantile(0.25)
# Q3_pc3_g4 = x_g4['CP3 (tercer ICE)'].quantile(0.75)
# IQR_pc3_g4 = Q3_pc3_g4 - Q1_pc3_g4
# x_5 = df_indi_pca_kmeans_ind8_tf['TCE_municipal'] == 'G5'
# x_g5 = df_indi_pca_kmeans_ind8_tf[x_5]
# Q1_g5 = x_g5['CP1 (ICE principal)'].quantile(0.25)
# Q3_g5 = x_g5['CP1 (ICE principal)'].quantile(0.75)
# IQR_pc1_g5 = Q3_g5 - Q1_g5
# Q1_pc2_g5 = x_g5['CP2 (segundo ICE)'].quantile(0.25)
# Q3_pc2_g5 = x_g5['CP2 (segundo ICE)'].quantile(0.75)
# IQR_pc2_g5 = Q3_pc2_g5 - Q1_pc2_g5
# Q1_pc3_g5 = x_g5['CP3 (tercer ICE)'].quantile(0.25)
# Q3_pc3_g5 = x_g5['CP3 (tercer ICE)'].quantile(0.75)
# IQR_pc3_g5 = Q3_pc3_g5 - Q1_pc3_g5
if (x['TCE_municipal'] == 'G0'):
if (x['CP1 (ICE principal)'] < Q1_g0-1.5*IQR_pc1_g0) or (x['CP1 (ICE principal)'] > Q3_g0+1.5*IQR_pc1_g0):
return 'Atípica en ICE principal'
elif (x['CP2 (segundo ICE)'] < Q1_pc2_g0-1.5*IQR_pc2_g0) or (x['CP2 (segundo ICE)'] > Q3_pc2_g0+1.5*IQR_pc2_g0):
return 'Atípica en segundo ICE'
elif (x['CP3 (tercer ICE)'] < Q1_pc3_g0-1.5*IQR_pc3_g0) or (x['CP3 (tercer ICE)'] > Q3_pc3_g0+1.5*IQR_pc3_g0):
return 'Atípica en tercer ICE'
else:
return 'Tipica'
elif (x['TCE_municipal'] == 'G1'):
if (x['CP1 (ICE principal)'] < Q1_g1-1.5*IQR_pc1_g1) or (x['CP1 (ICE principal)'] > Q3_g1+1.5*IQR_pc1_g1):
return 'Atípica en ICE principal'
elif (x['CP2 (segundo ICE)'] < Q1_pc2_g1-1.5*IQR_pc2_g1) or (x['CP2 (segundo ICE)'] > Q3_pc2_g1+1.5*IQR_pc2_g1):
return 'Atípica en segundo ICE'
elif (x['CP3 (tercer ICE)'] < Q1_pc3_g1-1.5*IQR_pc3_g1) or (x['CP3 (tercer ICE)'] > Q3_pc3_g1+1.5*IQR_pc3_g1):
return 'Atípica en tercer ICE'
else:
return 'Tipica'
elif (x['TCE_municipal'] == 'G2'):
if (x['CP1 (ICE principal)'] < Q1_g2-1.5*IQR_pc1_g2) or (x['CP1 (ICE principal)'] > Q3_g2+1.5*IQR_pc1_g2):
return 'Atípica en ICE principal'
elif (x['CP2 (segundo ICE)'] < Q1_pc2_g2-1.5*IQR_pc2_g2) or (x['CP2 (segundo ICE)'] > Q3_pc2_g2+1.5*IQR_pc2_g2):
return 'Atípica en segundo ICE'
elif (x['CP3 (tercer ICE)'] < Q1_pc3_g2-1.5*IQR_pc3_g2) or (x['CP3 (tercer ICE)'] > Q3_pc3_g2+1.5*IQR_pc3_g2):
return 'Atípica en tercer ICE'
else:
return 'Tipica'
elif (x['TCE_municipal'] == 'G3'):
if (x['CP1 (ICE principal)'] < Q1_g3-1.5*IQR_pc1_g3) or (x['CP1 (ICE principal)'] > Q3_g3+1.5*IQR_pc1_g3):
return 'Atípica en ICE principal'
elif (x['CP2 (segundo ICE)'] < Q1_pc2_g3-1.5*IQR_pc2_g3) or (x['CP2 (segundo ICE)'] > Q3_pc2_g3+1.5*IQR_pc2_g3):
return 'Atípica en segundo ICE'
elif (x['CP3 (tercer ICE)'] < Q1_pc3_g3-1.5*IQR_pc3_g3) or (x['CP3 (tercer ICE)'] > Q3_pc3_g3+1.5*IQR_pc3_g3):
return 'Atípica en tercer ICE'
else:
return 'Tipica'
# elif (x['TCE_municipal'] == 'G4'):
# if (x['CP1 (ICE principal)'] < Q1_g4-1.5*IQR_pc1_g4) or (x['CP1 (ICE principal)'] > Q3_g4+1.5*IQR_pc1_g4):
# return 'Atípica en ICE principal'
# elif (x['CP2 (segundo ICE)'] < Q1_pc2_g4-1.5*IQR_pc2_g4) or (x['CP2 (segundo ICE)'] > Q3_pc2_g4+1.5*IQR_pc2_g4):
# return 'Atípica en segundo ICE'
# elif (x['CP3 (tercer ICE)'] < Q1_pc3_g4-1.5*IQR_pc3_g4) or (x['CP3 (tercer ICE)'] > Q3_pc3_g4+1.5*IQR_pc3_g4):
# return 'Atípica en tercer ICE'
# else:
# return 'Tipica'
# elif (x['TCE_municipal'] == 'G5'):
# if (x['CP1 (ICE principal)'] < Q1_g5-1.5*IQR_pc1_g5) or (x['CP1 (ICE principal)'] > Q3_g5+1.5*IQR_pc1_g5):
# return 'Atípica en ICE principal'
# elif (x['CP2 (segundo ICE)'] < Q1_pc2_g5-1.5*IQR_pc2_g5) or (x['CP2 (segundo ICE)'] > Q3_pc2_g5+1.5*IQR_pc2_g5):
# return 'Atípica en segundo ICE'
# elif (x['CP3 (tercer ICE)'] < Q1_pc3_g5-1.5*IQR_pc3_g5) or (x['CP3 (tercer ICE)'] > Q3_pc3_g5+1.5*IQR_pc3_g5):
# return 'Atípica en tercer ICE'
# else:
# return 'Tipica'
else:
return 'nan'
#se aplica la función al último df con los resultados:
df_indi_pca_kmeans_ind8_tf['Atipicidad'] = df_indi_pca_kmeans_ind8_tf.apply(IQR_clusters_tf, axis = 1)
#se muestra el dataframe:
df_indi_pca_kmeans_ind8_tf
#para verificar, imprimimos los valores únicos en la columna Atipicidad.
df_indi_pca_kmeans_ind8_tf.Atipicidad.unique()
#imprimimos la frecuencia de los valores únicos en Atipicidad
df_indi_pca_kmeans_ind8_tf['Atipicidad'].value_counts()
#imprimimos el número de municipios por grupo de la tipología.
df_indi_pca_kmeans_ind8_tf['TCE_municipal'].value_counts()
#se guardan los resultados en un csv
df_indi_pca_kmeans_ind8_tf.to_csv(r'Resultados_Mun_Indic_PCA_Kmeans_Atip_ind8_tf.csv', index = None)